Javascript Syntax
Prepared by
Copyright By PowCoder代写 加微信 powcoder
Basic JS syntax
The syntax, expressions, and
VARIABLES & CONSTANTS
You can define them
using one of the
keywords →
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
// An immutable value available from the line // where the constant is defined
const constValue = ‘hey’;
// A mutable value available from the line // where the variable is defined
let variableValue = 0;
// A mutable value, old syntax. Hoists to the beginning // of the function scope or to the global scope,
// whatever is closer. Not recommended for use.
var anotherVariableValue = false;
PRINTING ARBITRARY VALUES TO CONSOLE
Just use console.log →
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09| 10| 11| 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
// Let’s say we have a constant storing a string
const name = ‘Bindi’;
// And a variable storing a number
let age = 22;
// And an object
let wildlifeWarrior = { name: name,
gender: ‘f’,
// This will print ‘Hello, world!’ to console
console.log(‘Hello, world!’);
// Additionally, you can print any value console.log(name); // Prints ‘Bindi’ console.log(‘name:’, name); // Prints ‘name: Bindi’ console.log(‘age: ‘ + age); // Prints ‘age: 22’
// This will print an object as a string
console.log(‘Person:’, wildlifeWarrior);
// Person: { name: ‘Bindi’, age: 22, gender: ‘f’ }
DATA TYPES
JavaScript is a
dynamically typed
language, meaning that
the same variable can
contain values of
different types →
01 | 02 | 03 | 04 | 05 | 06 | 07| 08 | 09 | 10 | 11 | 12 | 13| 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
let value;
// A float or integer number
value = 0.1;
// A string, double quotes “” can also be used
value = ‘some-string’;
// In JavaScript, null is a separate type
value = null;
// This type represents no value and no variable
value = undefined;
// A boolean value, either true or false
value = true;
// A unique value
value = Symbol();
// An object, which is basically a dictionary
// of dynamically typed values identified by their keys value = { key: ‘hey’, anotherKey: 10 };
DATA TYPES
Functions are first-
class citizens, meaning
that they can be
assigned to variables
and can be referenced →
01 | 02 | 03 | 04 | 05| 06 | 07 | 08 | 09 | 10| 11 | 12 | 13 | 14 | 15 | 16| 17| 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
let value;
// An anonymous function
value = (param1, param2) => {
console.log(param1, param2); };
// A normal function
value = function(param) {
console.log(‘param =’, param); };
// Function can be defined without assigning it // to a variable, in that case, it hoists function foo(bar) {
// If number, adds 1 to it, otherwise concatenates it
return bar + 1; }
// Calling a function
const result = foo(10); value(result); // Prints ‘param = 11’
// A big integer number
value = BigInt(9007199254740991);
DATA TYPES
You can always find out
the type of the value
that the varable
currently holds, at
However, in some cases,
you’d need a more
complex check
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
let value; value = 0.1;
console.log(typeof value); // Prints ‘number’ value = ‘some-string’;
console.log(typeof value); // Prints ‘string’
value = null; console.log(typeof
value = undefined; console.log(typeof
value = true; console.log(typeof
value = Symbol(); console.log(typeof
value); // Prints ‘object’ value); // Prints ‘undefined’ value); // Prints ‘boolean’ value); // Prints ‘symbol’
DATA TYPES
You can always find out
the type of the value
that the varable
currently holds, at
However, in some cases,
you’d need a more
complex check
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
let value;
value = { key: ‘hey’, anotherKey: 10 };
console.log(typeof value); // Prints ‘object’ value = function() { /* … */ };
console.log(typeof value); // Prints ‘function’
value = BigInt(9007199254740991); console.log(typeof value); // Prints ‘bigint’
DATA TYPES
undefined is also the type of a variable that hasn’t been assigned a value yet →
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
let value;
console.log(typeof value); // Prints ‘undefined’
// For more information on data types, // visit the MDN page:
// http://mdn.io/Data_structures
// I also recommend watching this old but gold talk // by :
// https://www.destroyallsoftware.com/talks/wat
// This talk makes fun of some JS things like undefined == null
// being true, and
undefined === null // being false
TYPE CONVERSIONS
It’s possible to
convert values of one
type into another, for
some of the supported
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
let value = 10;
let strValue = value.toString();
// or: let strValue = value + ”;
let numValue = parseInt(strValue, 10);
// or: let numValue = parseFloat(strValue); // or: let numValue = +strValue;
let bigIntValue = BigInt(numValue);
// or: let bigIntValue = BigInt(strValue);
let numValue = Number(bigIntValue);
// or: let numValue = parseInt(bigIntValue, 10);
COMPARING VALUES 07| 08 |
There is a strict
equality check and a
loose equality check,
and the strict check is
generally preferred
whenever possible →
09 | 10 | 11 | 12 | 13| 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
01 | 02 | 03 | 04 | 05 | 06 |
let value = 10;
let anotherValue = ’10’;
// With a loose equality check (aka ‘==’), two variables // are considered as holding identical values console.log(value == anotherValue); // Prints ‘true’
// With a strict equality check (aka ‘===’), the result // will indicate that the stored values are different console.log(value === anotherValue); // Prints ‘false’
// Comparing with an implicit type case can result // in a pretty weird outcome and should be avoided // when possible
const str = ‘[object Object]’;
const obj = { catsSay: ‘meow’, dogsSay: ‘woof’ }; console.log(str == obj); // Prints ‘true’ ̄\_( )_/ ̄ console.log(str === obj); // Prints ‘false’
// For more information, please check out these pages:
// https://mdn.io/Equality_comparisons_and_sameness
// http://ecma-international.org/ecma-262/5.1/#sec-11.9.3
Object, Array, Map, Set
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14| 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
// An object is a dictionary of dynamically typed values
const obj = { key: ‘some-value’, anotherKey: 10.2 }; console.log(obj.key); // Prints ‘some-value’ console.log(obj[‘key’]); // Prints ‘some-value’
// An array is an indexed list of dynamically typed // values. Every Array is also an object.
const arr = [‘first value’, 2, obj]; console.log(arr[0]); // Prints ‘first value’ console.log(arr.length); // Prints ‘3’ console.log(typeof arr); // Prints ‘object’
// A Map is an object that can use any value as a key // (not only strings) and preserves the original
// element order.
const map = new Map();
map.set(‘one’, 1); console.log(map.get(‘one’)); // Prints ‘1’
// A Set is an object that contains unique values
const set = new Set();
set.add(‘one’);
set.add(‘one’); // ‘one’ isn’t added the second time console.log(set.has(‘one’)); // Prints ‘true’
CONDITIONALS
Conditionals look like
their alternatives in
other C-like languages
The value in
parentheses
automatically gets
casted to a boolean
01 | 02 | 03 | 04 | 05 | 06| 07 | 08 | 09 | 10 | 11| 12 | 13| 14 | 15 | 16 | 17 | 18| 19 | 20| 21 | 22| 23 | 24 | 25 |
// One-liner if condition
if (condition) doSomething(); // If condition is truthy
// Multiline if
if (condition) {
// If condition is truthy
// If with else
if (confition) {
// If condition is truthy
// If condition is falsy
// If with multiple branches
if (condition1) {
// If condition1 is truthy
else if (condition2) {
// If condition2 is truthy
// If both condition1 and condition2 are falsy
CONDITIONALS
Using the switch statement often is more convenient and improves the code readability →
Don’t forger about the break at the end of each case!
01 | 02 | 03 | 04 | 05 | 06| 07| 08| 09| 10| 11| 12| 13| 14| 15| 16| 17| 18| 19| 20| 21 | 22 | 23 | 24 | 25 |
const value = 5;
// For mulitple branches, it’s often more // convenient to use a switch-case block switch (value) {
// If value equals to 0, the below code runs console.log(‘No items in the bag!’)
// If value equals to 1, the below code runs console.log(‘One item is in the bag!’); break;
// If value equals to 2, the below code runs console.log(‘A couple of items is in the bag!’); break;
// If value isn’t 0, 1, or 2, the below code runs console.log(‘Lots of items are in the bag’);
CONDITIONALS
Inline if, aka the
Ternary operator, is a
convenient way to write
less code and make it
easier to understand →
01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14| 15 | 16 | 17 | 18 | 19| 20 | 21 | 22 | 23 | 24 | 25 |
// Inline if (aka the ternary operator)
condition ? ifTrue() : ifFalse();
// It is an operator, meaning that it returns a value
const result = condition ? valIfTrue() : valIfFalse(); // Additionally, you can use lazy || and && operators
condition && ifTrue() || ifFalse();
// The above also returns a value
// (this is also known as rvalue in some languages) const result = condition && valIfTrue() || valIfFalse();
// Thanks to the && operator, it’s possible to write // a short version of a one-liner if:
condition && runSomething();
// which is a single line equivalent to
if (condition) {
runSomething(); }
CONDITIONALS
As said above, the
condition inside
parentheses gets auto-
casted to a boolean
However, to avoid
accidental unexpected
bugs, still, you must
understand how the type
casting works →
01 | 02| 03 | 04 | 05 | 06| 07 | 08 | 09 | 10| 11 | 12 | 13 | 14| 15 | 16 | 17 | 18| 19 | 20 | 21 | 22| 23 | 24 | 25 |
if (true) {
console.log(‘Always prints’); }
if (false) {
console.log(‘Never prints’); }
if (‘hey’) {
console.log(‘Always prints’); }
console.log(‘Never prints’); }
if (‘0’) {
console.log(‘Always prints’); }
console.log(‘Never prints’); }
CONDITIONALS
As said above, the
condition inside
parentheses gets auto-
casted to a boolean
However, to avoid
accidental unexpected
bugs, still, you must
understand how the type
casting works →
01 | 02| 03 | 04 | 05 | 06| 07 | 08 | 09 | 10| 11 | 12 | 13 | 14| 15 | 16 | 17 | 18| 19 | 20 | 21 | 22| 23 | 24 | 25 |
console.log(‘Always prints’); }
if (null) {
console.log(‘Never prints’); }
if (undefined) {
console.log(‘Never prints’); }
if ({ x: ‘test’ }) {
console.log(‘Always prints’); }
if (Symbol()) {
console.log(‘Always prints’); }
if (function x() {}) {
console.log(‘Always prints’); }
CONDITIONALS
And sometimes, it gets
really tricky →
01 | 02| 03 | 04 | 05 | 06| 07 | 08 | 09 | 10| 11 | 12 | 13| 14| 15 | 16 | 17 | 18| 19 | 20 | 21 | 22| 23 | 24 | 25 |
if (BigInt(1020202)) {
console.log(‘Always prints’); }
if (BigInt(0)) {
console.log(‘Never prints’); }
if (‘1’ – 1) {
console.log(‘Never prints’); }
if (+’0′) {
console.log(‘Never prints’); }
if (new String(”)) {
console.log(‘Always prints’); }
if (new Number(0)) {
console.log(‘Always prints’); }
JavaScript supports the
same syntax for the
loops that many curly
bracket syntax
languages like C do
01 | 02 | 03| 04 | 05 | 06 | 07 | 08 | 09| 10| 11 | 12 | 13 | 14 | 15 | 16| 17| 18| 19| 20 | 21| 22 | 23 | 24 | 25 |
// Good old for loop
for (let i = 0; i < 100; i++) {
console.log(i); }
// An equivalent while loop
let i = 0;
while (i < 100) {
console.log(i);
// Or equivalent do...while loop
let i = 0; do {
++i; if(i>=100){
console.log(i); } while (true);
01 | 02 | 03| 04| 05| 06| 07|
// Defining a new class
class Snack {
// A consuctor that will be auto-called constructor(calories, name) {
this.caloriesRemaining = calories;
this.name = name; }
// One of attached functions, usually called ‘methods’
this.caloriesRemaining -= 100; }
Modern JavaScript also 08|
supports classes,
allowing for a
convenient way to
implement abstractions
and ship the data along
with the functions that
can process it →
09| 10| 11| 12| 13| 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
A JavaScript class can
be extended and can
have static members
01 | 02| 03| 04| 05| 06| 07| 08| 09 | 10 | 11 | 12| 13 | 14| 15| 16| 17 | 18 | 19 | 20| 21 | 22| 23| 24| 25 |
class Snack { constructor(calories, name) {
this.caloriesRemaining = calories;
this.name = name; }
this.caloriesRemaining -= 100; }
class Pizza extends Snack {
static caloriesPerGram = 2.66;
constructor(weightInGrams) {
super(Pizza.caloriesPerGram * weightInGrams, ‘XL’); }
class Crisps extends Snack {
static caloriesPerGram = 5.36;
constructor(weightInGrams) {
super(Crisps.caloriesPerGram * weightInGrams, ‘Thins’); }
01 | CLASSES 02| 03| 04| 05 | 06| 07| patterns established in 08| 09| 10| 11| 12| 13 |
class Meal { constructor(snacks) {
this.snacks = snacks; }
eatSome() {
for (let i = 0; i < this.snacks.length; i++) {
const snack = this.snacks[i]; console.log('Chewing', snack.name); snack.chew();
With classes, you can
use all features and
object-oriented
programming
However, internally,
each class is just a
constructor function,
because JavaScript OOP
is based on
'prototyping'
logCalories() {
for (let i = 0; i < this.snacks.length; i++) {
22 | console.log(typeof Meal); // Prints 'function' 23 |
console.log(snack.name, ': ', snack.caloriesRemaining);
const snack = this.snacks[i];
A class is just a
constructor function,
and a class instance is
01 | 02| 03| 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
const snacks = [ new Pizza(800),
new Crisps(150), ];
const meal = new Meal(snacks); meal.logCalories(); meal.eatSome(); meal.logCalories();
console.log(typeof Meal); // Prints 'function' console.log(typeof meal); // Prints 'object'
SIMPLE FIBONACCI SEQUENCE GENERATOR IN JAVASCRIPT
So hopefully, this
example's got a bit
easier to understand →
01 | 02| 03| 04| 05 | 06| 07| 08| 09 | 10| 11| 12| 13| 14| 15| 16| 17| 18| 19 | 20| 21 | 22 | 23 | 24 | 25 |
const fib = (n) => { if(n===0){
return 0; }
if(n===1){
return 1; }
let current = 0;
let previous = 1;
let prePrevious = 0;
// Iterative calculation for(leti=0;i