Javascript String Primitives And Objects

Description

Javascript String Primitives And Objects



// Create a simple string primitive from a literal
let myStringPrimitive = "Hello World";

// Create a more sophisticated String object using the String object constructor
let myStringObject = new String("Hello World");

// We can also create a string primitive by omitting the "new" keyword..
let myStringPrimitive2 = String("Hello World");

// Accessing the length property of strings can be done on variables (be they primitives or objects) and also on literals (another form of a primitive)
console.log( myStringPrimitive.length);    // "11"
console.log( myStringPrimitive2.length);    // "11"
console.log( "Hello World".length );    // "11"
console.log( myStringObject.length);    // "11"

console.log( typeof myStringPrimitive );    // "string"
console.log( typeof myStringPrimitive2 );    // "string"
console.log( typeof "Hello World" );    // "string"
console.log( typeof myStringObject );    // "object"

console.log( typeof myStringObject.valueOf() );    // "string"



PreviousNext

Related