Data types

A variable in JavaScript can contain any data. A variable can at one moment be a string and later receive a numeric value:

// no error
let message = "hello";
message = 123456;

在程式語言中,所謂的 “dynamically typed”, 指的是雖然有type 但是變數不會侷限於某個type .

A number

let n = 123;
n = 12.345;

四則運算:加減乘除 特殊值: Infinity, -Infinity and NaN.

或者
javascript alert( Infinity ); // Infinity

A string

三種方式表示雙引號:

  1. Double quotes: "Hello".
  2. Single quotes: 'Hello'.
  3. Backticks: `Hello`.
let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed ${str}`;

in ${…}, for example:

let name = "John";

// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!

// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
echo off
set x="xxx"
echo %x%

錯誤: 因為雙引號不作用

alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)

沒有 character 型態。 例如,C, java 有形態 char但是JavaScript沒有。只有string.。

A boolean

兩個值: true and false.

let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked

Boolean values also come as a result of comparisons:

let isGreater = 4 > 1;

alert( isGreater ); // true (the comparison result is "yes")

The “null” value

這個值null,有它自己的型態。

let age = null;

In JavaScript null is not a “reference to a non-existing object” or a “null pointer” like in some other languages.

“nothing”, “empty” or “value unknown”.

The code above states that the age is unknown or empty for some reason.

The “undefined” value

undefined 也是有它自己的型態。 意思是,沒有指派值。

let x; //已經被宣告,但是沒定義

alert(x); // shows "undefined"

雖然也可以拿來指派給變數,但是沒有意義.

let x = 123;

x = undefined;

alert(x); // "undefined"

前面的null也是一個值,

let x=null

但是,程式人員指派這個null的意思是說,我們要確認他是空的。但是undefiend的原本意義在讓我們知道這是空值。

Objects and Symbols

more ...

The typeof operator

typeof 也是一個運算元。

語法有兩種:

  1. As an operator: typeof x.
  2. Function style: typeof(x).
```javascript
typeof undefined // "undefined"
typeof 0 // "number"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object"  (1)
typeof null // "object"  (2)
typeof alert // "function"  (3)

The last three lines may need additional explanations:

  1. Math 是一個內建的物件。more
  2. typeof null 的運算結果 "object". 這個結果是錯的,這是已知的錯誤,但是為了相容性,仍然留著,這是一個值。