post-css-position

5 Useful JavaScript Basic Concepts that Must be Mastered

JavaScript is easy to learn, though it has some interest facts. This article introduces 5 JavaScript basic concepts, including object, conditional judgement, loop, map and set, and iterable.

This is the second article in the JavaScript Definitive Guide. In the first post, we have studied some basic knowledge of JavaScript, including the history, data types and variables. If you don’t, it is better to read that post first.

There will be several code snippets in this article. I highly suggest you to run each of the snippet and watch the behavior. It is the best way to learn JavaScript from my view.

JavaScript Basic Concept 1 – Object

A JavaScript object is an unordered collection that consists of several key-value pairs.

JavaScript objects are used to describe an object in the real world. For example, to describe the naughty child “John”, we can create an object with several key-value pairs:

var John = {
    name: 'John',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70, // Meter
    weight: 65, // KG
    score: null
};

JavaScript uses one {...} to represent an object, and key-value pairs are declared in form xxx: xxx, separated by a semicolon. Note that the last key-value pair does not need to be ended with ,. If it is added, some browsers (such as the lower version of IE) will report an error.

The above object declares a name attribute with value 'John', the birth attribute with value 1990, and some other attributes. Finally, after assigning this object to the variable John, you can get the attribute of John through the variable John:

John.name; // 'John'
John.birth; // 1990

Access properties are done through the .operator, but this requires the property name to be a valid variable name. If the attribute name contains special characters, it must be enclosed inside ''. E.g.,

var Bailey = {
    name: 'Bailey',
    'middle-school': 'No.1 Middle School'
};

The attribute name middle-school is not a valid variable and needs to be '' enclosed. This property cannot be accessed with .operator. Instead we use ['xxx']:

Bailey['middle-school']; // 'No.1 Middle School'
Bailey['name']; // 'Bailey'
Bailey.name; // 'Bailey'

It can also use Bailey['name']to access name property, but Bailey.name is more concise. When writing JavaScript codes, we should use the standard variable name as much as possible, so that we can access a property directly through the form object.prop.

In fact, all properties of a JavaScript object are strings, but the type of a value can be of any data type.

What if I access a property that doesn’t exist? JavaScript stipulates that accessing a property that does not exist will not report an error, but instead returns undefined:

'use strict';

var Someone = {
    name: 'someone'
};

console.log(Someone.name);
console.log(Someone.age); // undefined

Since JavaScript objects are dynamic types, you are free to add or remove attributes to an object:

var John = {
    Name: 'John'
};
John.age; // undefined
John.age = 18; // Add an age attribute
John.age; // 18
delete John.age; // delete the age attribute
John.age; // undefined
delete John['name']; // delete the name attribute
John.name; // undefined
delete John.school; // delete a non-existent school attribute will not give an error

If we want to detect if an object has an specific attribute, we can use the in operator:

var John = {
    name: 'John',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70, // Meter
    weight: 65, // KG
    score: null
};
'name' in John; // true
'grade' in John; // false

But be careful, when you creating an object, some attributes are inherited from the object’s parent. For instance, we do not declare the toString property in John. And the in operator returns true.

'toString' in John; // true

Because toString is defined in the object object, and all objects will eventually point to the object in the prototype chain. So John also has the toString property. Actually, it is a function.

To determine if an attribute is owned by John itself, rather than inherited, you can use the hasOwnProperty() method:

var John = {
    name: 'John'
};
John.hasOwnProperty('name'); // true
John.hasOwnProperty('toString'); // false

I highly recommend you to test above codes. Because practise is the best way to learn JavaScript.

JavaScript Basic Concept 2 – ObjectConditional Judgment

JavaScript use if () { ... } else { ... } to make conditional judgments. For example, to display different content based on age, you can use the if statement to achieve the following:

var age = 20;
if (age >= 18) { // If age >= 18 is true, execute the if statement block
    alert('adult');
} else { // Otherwise execute the else statement block
    alert('teenager');
}

The else statement is optional. If the statement block contains only one statement, {} can be omitted:

var age = 20;
if (age >= 18)
    alert('adult');
else
    alert('teenager');

The danger of omitting {} is that if you later want to add some statements and forget to write {}, you may change the if...else... semantics, for example:

var age = 20;
if (age >= 18)
    alert('adult');
else
    console.log('age < 18'); // add a line
    alert('teenager'); // <- This line of statements is no longer in the control of else.

The else clause of the above code is actually only responsible for execution console.log('age < 18');, and the original control scope is alert('teenager');. However, this line of code alert('teenager'); will be executed every time.

On the contrary, with {}, the statement executes correctly:

var age = 20;
if (age >= 18) {
    alert('adult');
} else {
    console.log('age < 18');
    alert('teenager');
}

IMPORTANT: Always writing conditional statements with {}.

Multi-Line Conditional Judgment

If you want to judge the conditions more carefully, you can use multiple if...else.... For example:

var age = 3;
if (age >= 18) {
    alert('adult');
} else if (age >= 6) {
    alert('teenager');
} else {
    alert('kid');
}

The if...else...combination of the above multiples actually corresponds to two layers if...else...:

var age = 3;
if (age >= 18) {
    alert('adult');
} else {
    if (age >= 6) {
        alert('teenager');
    } else {
        alert('kid');
    }
}

But we usually write else if together to increase readability.

Please note that the execution characteristics of the if...else... statement are two-choice. In a if...else...statement, if a certain condition is established, the subsequent judgment will not be continued.

Try to explain why the following code shows teenager:

'use strict';
var age = 20;
if (age >= 6) {
     console.log('teenager');
 } else if (age >= 18) {
     console.log('adult');
 } else {
     console.log('kid');
 }

Because the value of age is 20, it actually satisfies the conditional age >= 6 at the same time age >= 18, which indicates that the order of conditional judgment is very important. Please fix it and let it show adult.

What if the conditional judgment statement is not true or false. E.g:

var s = '123';
if (s.length) { // the result is 3
    //
}

JavaScript treats null, undefined, 0, NaN and empty strings '' as false. Other values ​​are considered as true. So the result of the above code condition is judged to be true.

Exercise 1

John is 1.75 meters tall and weighs 80.5kg. Please help John calculate his Body mass index according to the BMI formula (weight divided by the square of height).

John is 1.75 meters tall and weighs 80.5kg. Please help John calculate his Body mass index according to the BMI formula (weight divided by the square of height).

  • Below 18.5: too light
  • 18.5-25: Normal
  • 25-28: Overweight
  • 28-32: Obesity
  • Above 32: severe obesity

Use if...else... judgment and display the result:

'use strict';

var height = parseFloat(prompt('Please enter the height in meters :'));
var weight = parseFloat(prompt('Please enter the weight in kg :'));

JavaScript Basic Concept 3 – Loop

To calculate 1+2+3, we can write the expression directly:

1 + 2 + 3; // 6 

To calculate 1+2+3+…+10, you can barely write it.

However, to calculate 1+2+3+…+10000, it is impossible to directly write an expression.

In order for the computer to calculate thousands of iterations, we need looping statements.

There are two types of JavaScript loops. One is the for loop that loops through the statement block with initial conditions, end conditions, and increment conditions:

var x = 0;
var i;
for (i=1; i<=10000; i++) {
    x = x + i;
}
x; // 50005000

Let us analyze control conditions of the loop:

  • i=1 This is the initial condition, setting the variable i to 1;
  • i<=10000 This is the judgment condition. When it is satisfied, it will continue to loop. If it is not satisfied, it will exit the loop.
  • i++ This is the increment condition after each loop. Since the variable i will be incremented by 1 after each loop, it will eventually i<=10000 exit the loop after satisfying the judgment condition after several cycles.

Exercise 2

Using the results of the for loop calculation 1 * 2 * 3 * ... * 10:

'use strict';
var x = ?;
var i;
for ...

if (x === 3628800) {
    console.log('1 x 2 x 3 x ... x 10 = ' + x);
}
else {
    console.log('calculation error');
}

The most common place for loops is to use an index to iterate through an array:

var arr = ['Apple', 'Google', 'Microsoft'];
var i, x;
for (i=0; i<arr.length; i++) {
    x = arr[i];
    console.log(x);
}

The three conditions of the loop can be omitted. If the judgment condition does not exist, you must use the break statement to exit the loop, otherwise it is an infinite loop:

Var x = 0;
For (;;) { // will loop indefinitely
     If (x > 100) {
         Break; // exit the loop by a if judgment
     }
     x ++;
}

For … in

One variant of for is for ... in, which loops through all the properties of an object:

var o = {
    name: 'Jack',
    age: 20,
    city: 'Los Angeles'
};
for (var key in o) {
    console.log(key); // 'name', 'age', 'city'
}

To filter out all inherited properties, use hasOwnProperty():

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key); // 'name', 'age', 'city'
    }
}

Since an Array is also an object, and the index of each of its elements is treated as an object’s property, the for ... in loop can loop directly out of the index:

var a = ['A', 'B', 'C'];
for (var i in a) {
    console.log(i); // '0', '1', '2'
    console.log(a[i]); // 'A', 'B', 'C'
}

Note that the for ... in loop of an Array gets String as the index rather than Number.

While

for loops are very useful when you are aware of the initial and end conditions of a loop. The above-mentioned for loop that ignores the condition is easy to see the logic of the loop, and the while loop is better at this time .

The while loop has only one judgment condition. If the condition is satisfied, it will continue to loop. If the condition is not satisfied, it will exit the loop. For example, we want to calculate the sum of all odd numbers within 100, which can be implemented with a while loop:

var x = 0;
var n = 99;
while (n > 0) {
    x = x + n;
    n = n - 2;
}
x; // 2500

In the loop, the internal variable is n continuously decremented until it becomes -1, the while condition is no longer satisfied , and the loop exits.

Do … While

The last loop is a do { ... } while() loop. The only difference between while and the do { ... } while() loop is that instead of judging the condition at the beginning of each loop, the condition is evaluated each time the loop is executed:

var n = 0;
do {
    n = n + 1;
} while (n < 100);
n; // 100

Be careful with do { ... } while() loops, it will be executed at least once. for and while loops may not be executed at once.

Exercise 3

Use a loop to iterate over each name in the array and display Hello, xxx!:

'use strict'; 
var arr = ['Bart', 'Lisa', 'Adam']; 
for ...

Try both for loops and while loops and traverse in both positive and negative order.

Summary of Loop

Loops are an effective way for computers to do repetitive tasks. Sometimes, if the code is written incorrectly, it will cause the program to fall into an “infinite loop,” which is to loop forever. The infinite loop of JavaScript will prevent the browser from displaying or executing the logic of the current page. Some browsers will hang directly. Some browsers will prompt you to terminate the execution of JavaScript after a period of time. Therefore, pay special attention to the problem of “infinite loop”.

When writing looping code, be careful to write initial conditions and judgment conditions, especially boundary values. We should emphasis that i < 100 and i <= 100 have different determination logic.

JavaScript Basic Concept 4 – Map and Set

The default object representation of JavaScript {} can be thought of as a data structure Map or Dictionary in another language , a set of key-value pairs.

But JavaScript objects have a small problem, that is, the keys must be strings. But in fact, Number or other data types are very reasonable as keys.

To solve this problem, the latest ES6 specification introduces new data types Map. To test if your browser supports the ES6 specification, execute the following code. If the browser reports a ReferenceError error, then you need to change to a browser that supports ES6:

'use strict';
var m = new Map();
var s = new Set();
console.log('Your browser supports Map and Set!');

Map

Map is a structure of a set of key-value pairs with an extremely fast search speed.

For example, suppose you want to find the corresponding grade according to the classmate’s name. If you use the Array implementation, you need two Array:

var names = ['Michael', 'Bob', 'Tracy'];
var scores = [95, 75, 85];

Given a name, to find the corresponding score, you must first find the corresponding location in the names, and then take the corresponding score from the scores, the longer the Array, the longer it takes.

If you use a Map to implement, you only need a comparison table of “name” – “score”, and find the score directly according to the name. No matter how big the table is, the search speed will not slow down. Write a Map in JavaScript as follows:

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95

Initialization of a Map requires a two-dimensional array, or directly initializes an empty MapMapHas the following methods:

var m = new Map(); // Empty Map
m.set('Adam', 67); // Add new key-value m.set('Bob', 59);
m.has('Adam'); // Check if key 'Adam' exists: true
m.get('Adam');
m.delete('Adam'); // Delete key 'Adam' m.get('Adam'); // undefined

Since a key can only correspond to one value, if multiple values ​​are placed on one key, the latter value will flush the previous value:

var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam'); // 88 

Set

Similar to Map, Set is also a collection of keys, but does not store value. Since the key cannot be repeated, a Set has no duplicate key in it.

To create a Set, you need to provide a Array as input, or create an empty one Set directly:

var s1 = new Set(); // Empty Set
var s2 = new Set([1, 2, 3]); // A set contains 1, 2, 3.

Repeating elements are automatically filtered out in a Set:

var s = new Set([1, 2, 3, 3, '3']);
s; // Set {1, 2, 3, "3"}

Note that numbers 3 and strings '3' are different elements.

The add(key)method can be used to add elements to a Set and can be added repeatedly, but it will not be effective:

s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // Still Set {1, 2, 3, 4}

Elements can be removed by method delete(key):

var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}

Summary of Map and Set

Map and Set are new data types of the ES6 standard. Please decide whether to use it according to the support of the browser.

JavaScript Basic Concept 5 – Iterable

The travel of an Array can be done with a subscript loop. Traversing Map and Set cannot use subscripts. In order to unify collection types, the ES6 standard introduces new iterable type. ArrayMap and Set are all belonged to the iterable type.

Collections with iterable type can be traversed by the new loop type for ... of.

It is the new syntax introduced by ES6. Please test if your browser supports:

'use strict';
var a = [1, 2, 3];
for (var x of a) {
}
console.log('Your browser supports for ... of');

Use a for ... of loop to traverse the collection, as follows:

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // Loop over an Array
    console.log(x);
}
for (var x of s) { // Loop over a Set
    console.log(x);
}
for (var x of m) { // Loop over a Map
    console.log(x[0] + '=' + x[1]);
}

You may have questions, what is the difference between for ... of and for ... in?

The for ... in loop traverses the attribute name of the object due to historical issues. An Array array is actually an object, and the index of each element of the array is treated as an attribute.

When we manually add extra properties to an Array object, the for ... in loop will have unexpected effects:

var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x in a) {
    console.log(x); // '0', '1', '2', 'name'
}

The above loop includes the name attribute, but the length attribute of the Array is not included.

The loop for ... of completely fixes these problems, it only loops through the elements of the collection itself:

var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x of a) {
    console.log(x); // 'A', 'B', 'C'
}

This is why a new for ... of loop is introduced .

However, a better way is to use the iterable built-in forEach method directly , which receives a function as its parameter that automatically calls back the function in each iteration. Take Array as an example:

'use strict';
Var a = ['A', 'B', 'C'];
a.forEach(function (element, index, array) {
     // element: points to the value of the current element
     // index: points to the current index
     // array: points to the Array object itself
     console.log(element + ', index = ' + index);
 });

Note that the forEach() method was introduced in the ES5.1 standard and you need to test whether the browser supports it.

Set is similar to Array, but a Set does not has index, so the first two arguments to the callback function is the element itself:

var s = new Set(['A', 'B', 'C']);
s.forEach(function (element, sameElement, set) {
    console.log(element);
});

The Map callback function parameters are valuekey and the map itself:

var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
m.forEach(function (value, key, map) {
    console.log(value);
});

If you are not interested in certain parameters, JavaScript function calls can be ignored because they do not require parameters to be consistent. For example, just need to get Array in element:

var a = ['A', 'B', 'C'];
a.forEach(function (element) {
    console.log(element);
});

Closing Words

Aha! Thanks for reading this article.

It is my pleasure to have you reading my boring words. I think this is the best way to learn JavaScript. But you are gradually becoming a JavaScript expert. Be proud of yourself. And make me a promise that you will continue to follow this tutorial.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *