JavaScript (2) Values and Types

1. Values and Types:

Each variable uses different types to store different kinds of values. e.g. "string" is used to save the text and "number" is used to save the numerical values.

Check the type of literal value with typeof():

console.log(typeof("42"));
// string

console.log(typeof(42));
// number

The type of the variable is depend on the content saved in the variable:

var a = "42";
console.log(typeof(a));
// string

var a = 42;
console.log(typeof(a));
// number

The type defines the behaviour of the variable and literal value:

var a = "42" + "42";
console.log(a);
// "4242"

var a = 42 + 42;
console.log(a);
// 84

var a = "42" + 42;
console.log(a);
// "4242"

The string ("42") can't add with the number (42). The number (42) is converted to the string ("42") automatically.


2. Converting Between Types:

var a = "42";
var b = Number( a );
console.log( a );
// "42"

console.log( b );
// 42

Number() is a built-in function which performs the explicit coercion from any other type to the number type.


3. Strictly equal:

Sometimes we to testing equality of the variables.

=== operator testing the equality of the variables strictly:

42 === 42;
// true

42 === "42";
// false

=== returns true if the variable has equal value and equal type.


4. Loosely equal:

== operator testing the equality of the variables loosely:

"42" == 42;
// true

== converts the left-hand side to number implicitly and testing the equality.


Reference

[1] Kyle Simpson, You Don't Know JS Series, O'Reilly Media (2014)

留言

熱門文章