JavaScript is one of the most popular programming languages for web programming.
In this article, we’ll look at the basic syntax of modern JavaScript.
Arrow function
const sum = (a, b) => a + b
sum(1, 2)
returns 3.
Default parameters
function print(a = 5) {
console.log(a)
}
print()
logs 5.
let scope
We can use let
to declare variables:
let a = 3
if (true) {
let a = 10
console.log(a)
}
console.log
should log 10.
const
const
variables can only be assigned once when we initialize it:
const a = 11
We’ll get an error if we try to assign a
again.
Multiline String
We can create multine string with backticks (`):
console.log(`
This is a
multiline string
`)
Template Strings
We can interpolate expressions with ${}
:
const name = 'james'
const message = `Hello ${name}`
Then message
is 'Hello james'
String includes()
We can use the includes
method to check if a string has the given substring.
So
'apple'.includes('pl')
returns true
.
String startsWith()
The startsWith
method lets us check if a string starts with a given substring:
'apple'.startsWith('ap')
String repeat()
We can use the repeat
method to repeat a string:
'ab'.repeat(3)
returns ‘ababab’
.
Destructuring Array
We can use the destructuring syntax to assign array entries to variables.
For instance, we write:
let [a, b] = [3, 10];
Then a
is 3 and b
is 10.
Destructuring Object
We can assign object properties to variables with the destructuring syntax.
For example, if we have:
let obj = {
a: 15,
b: 20
};
let {
a,
b
} = obj;
Then a
is 15 and b
is 20.
Object Property Assignement
We can assign properties to objects with the object property assignment syntax.
For instance, we write:
const a = 2
const b = 5
const obj = {
a,
b
}
Then obj
is:
{a: 2, b: 5}
Object Function Assignment
We can add methods to an object with the shorthand syntax:
const obj = {
a: 'foo',
b() {
console.log('b')
}
}
Then we can call obj.b()
to log 'b'
.
Spread Operator
The spread operator lets us combine arrays into one.
For instance, we write:
const a = [1, 2]
const b = [3, 4]
const c = [...a, ...b]
And c
is [1, 2, 3, 4]
.
Object.assign()
The Object.assign
method lets us combine multiple objects into one.
For instance, we write:
const obj1 = {
a: 1
}
const obj2 = {
b: 2
}
const obj3 = Object.assign({}, obj1, obj2)
Then obj3
is { a: 1, b: 2 }
.
Object.entries()
We can get the object’s key-value pairs into an array with the Object.entries()
method.
For instance, we write:
const obj = {
frstName: 'james',
lastName: 'smith',
age: 22,
country: 'uk',
};
const entries = Object.entries(obj);
Then Object.entries
returns:
[
[
"frstName",
"james"
],
[
"lastName",
"smith"
],
[
"age",
22
],
[
"country",
"uk"
]
]
Conclusion
JavaScript comes with useful syntax and methods in the standard library we can use.