Slide navigation: Forward with space bar, →, or PgDn. Backwards with ← or PgUp.
<html> <head> <title>My First JavaScript Program</title> <script type="text/javascript"> const a = 6 const b = 7 window.alert(a * b) </script> </head> <body></body> </html>
false
and true
null
and undefined
typeof
operator yields string describing type:
typeof 42 // Yields 'number'
let counter = 0 const PI = 3.141592653589793
counter = 'zero'
const
array or object can be mutated: const numbers = [1, 2, 7, 9] numbers[2] = 4 // Ok
const
over let
var
coutner = 1
ReferenceError
'use strict'
at the top of each source file.node
with --use-strict
command line option.typeof
with an undeclared variable:
typeof coutner // Yields 'undefined'
null
, undefined
, NaN
undefined
.undefined
if it exits without a return
statement.null
value denotes an “intentionally” absent value.null
NaN
denotes “Not a number”.undefined
(or NaN
).Number.MIN_SAFE_INTEGER
(-253+1 or -9,007,199,254,740,991) and Number.MAX_SAFE_INTEGER
(253-1 or 9,007,199,254,740,991).0.1 + 0.2
is 0.30000000000000004
parseInt
and parseFloat
functions convert strings to numbers:const notQuitePi = parseFloat('3.14')
parseFloat
) and methods (console.log
).Infinity
, -Infinity
, NaN
.parseFloat('pie')
is NaN
.BigInt
have suffix n
: 18889465931478580854784n
+ - * /
/
operator always yields a floating-point result: 1 / 2
is 0.5
%
produces the remainder: 42 % 10
is 2
, 1.1 % 0.3
is 0.2
**
raises to a power: 2 ** 10
is 1024
, 2 ** 0.5
is 1.4142135623730951
NaN
, so is the result: 10 * NaN
is NaN
counter += 10
counter++ const enigma = --counter // No longer considered good style
'3' * true
+
concatenates strings:
'Agent ' + counter // Non-string argument is converted to string
([] + [3]) * true
?Value | To Number | To String |
---|---|---|
A number | Itself | A string containing the digits of the number |
A string containing the digits of a number | The number value | Itself |
The empty string '' |
0 |
'' |
Any other string | NaN |
Itself |
false |
0 |
'false' |
true |
1 |
'true' |
null |
0 |
'null' |
undefined |
NaN |
'undefined' |
The empty array [] |
0 | '' |
An array containing a single number | The number | A string containing the digits of the number |
Other arrays | NaN |
The elements as strings, joined by commas |
Objects | Generally, NaN , but can be customized |
Generally, '[object Object]' , but can be customized |
'Hello'
or "Hello"
'\\\'\'\\\n'
contains \''\
and newline.const greeting = 'Hello 🌐'
\u{...}
for code points:
const greeting = 'Hello \u{1F310}'
greeting.length // 8 greeting[6] // Half of the UTF-16 code for 🌐
const destination = 'world' const greeting = `Hello, ${destination.toUpperCase()}!` // 'Hello, WORLD!'
${...}
:
greeting = `Hello, ${firstname.length > 0 ? `${firstname[0]}. ` : '' } ${lastname}`
greeting = `<div>Hello</div> <div>${destination}</div> `
` $ \
with backslashes.\
only escape ` $
:
path = String.raw`C:\Windows\System`
const harry = { name: 'Harry Smith', age: 42 }
harry.age = 39
harry.salary = 90000 delete harry.age
undefined
:
const boss = harry.supervisor // undefined
const field = 'Age' const harrysAge = harry[field.toLowerCase()]
const age = 42
const harry = { name: 'Harry Smith', age } // Same as age: age
const harry = { name: 'Harry Smith', 'favorite beer': 'IPA' } harry['favorite beer'] = 'Lager' // Can't use dot notation to access property
const harry = { name: 'Harry Smith', [field.toLowercase()] : 42 }
{ name: 'Harry Smith', age: 42, }
{
is parsed as the beginning of a block statement, not an object literal:
{} - 1 // An empty block statement, followed by -1
1 - {} // 1 - an empty object, yielding NaN
'0'
, '1'
, '2'
, and so on.const numbers = [1, 2, 3, 'many'] // Element types need not match
numbers['2'] // 3
numbers[2] // Also 3
—bracket operand is converted to string
const someNumbers = [, 2, , 9] //someNumbers[0]
isundefined
const developers = [ 'Harry Smith', 'Sally Lee', // Add more elements above ]
length
is one more than the highest index: someNumbers.length
is 4.numbers.lucky = true
typeof
returns 'object'
for arrays.Array.isArray(obj)
to test whether obj
is an array.'' + [1, 2, 3] // Yields '1,2,3'
const melancholyMagicSquare = [ [16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1] ]
melancholyMagicSquare[1][2] // Yields 11
{ "name": "Harry Smith", "age": 42, "lucky numbers": [17, 29], "lucky": false }
true
, false
, null
, arrays, and objects.JSON.stringify(obj)
, JSON.parse(str)
console.log(`harry=${JSON.stringify(harry)}`) // console.log(`harry=${harry}`) yields useless harry=[object Object]
console.log('harry=', harry) console.log({harry})
let [first, second] = numbers
first
and second
let first = numbers[0] let second = numbers[1]
let
, can set existing variables:
[second, first] = numbers
[x, y] = [y, x]
[first, second, ...others] = numbers // others
is an array holding the rest
numbers
is [42]
, second
is undefined
and others
is []
const harry = { name: 'Harry', age: 42 } let { name:harrysName
, age:harrysAge
} = harry //harrysName
isharry.name
,harrysAge
isharry.age
harrysName
, harrysAge
let { name, age } = harry
name
, age
let { name, ...rest } = harry
undefined
: let { nickname = 'None' } = harry // Setsnickname
to'None'
sinceharry
has nonickname
property
let { name, nickname = name } = harry // Bothname
andnickname
are set toharry.name
const config = ... // For example { separator: '; ' }
const { separator = ',', leftDelimiter = '[', rightDelimiter = ']' } = config
({ name, age }) = sally // Without(...)
, the{
would start a block
const field = 'Age' { [field.toLowerCase()]: value } = harry // Setsvalue
toharry[field.toLowerCase()]
const harry = { name: 'Harry', birthday: { day: 14, month: 3, year: 2000 } }
const { birthday: { year: harrysBirthYear } } = harry
// Declares the variable harrysBirthYear
and initializes it to 2000