JavaScript is a complex thing to master. If you’re a JavaScript developer at any level, it’s crucial to understand its core notions. This article covers 7 principles that any JS developer should be aware of, however it by no means covers everything a JS developer should know.
1. Value vs. Reference Variable Assignment
To write bug-free JavaScript, you must first understand how JavaScript assigns variables. If you don't understand this, you could easily develop code that changes values without your knowledge.
JavaScript always assigns variables by value. But this part is very important: when the assigned value is one of JavaScript’s five primitive type (i.e., Boolean, null, undefined, String, and Number) the actual value is assigned. However, when the assigned value is an Array, Function, or Object a reference to the object in memory is assigned.
Example time!
In the following snippet, var2 is set as equal to var1. Since var1 is a primitive type (String), var2 is set as equal to var1's String value and can be thought of as completely distinct from var1 at this point. Accordingly, reassigning var2 has not effect on var1.
let var1 = 'My string';
let var2 = var1;
var2 = 'My new string';
console.log(var1);
// 'My string'
console.log(var2);
// 'My new string'
Let’s compare this with object assignment.
let var1 = { name: 'Jim' }
let var2 = var1;
var2.name = 'John';
console.log(var1);
// { name: 'John' }
console.log(var2);
// { name: 'John' }
One might see how this could cause problems if you expected behavior like primitive assignment! This can get especially ugly if you create a function that unintentionally mutates an object.
2. Destructuring
Don’t be thrown off by JavaScript parameter destructuring! It’s a common way to cleanly extract properties from objects.
const obj = {
name: 'Joe',
food: 'cake'
}
const { name, food } = obj;
console.log(name, food);
// 'Joe' 'cake'
If you want to extract properties under a different name, you can specify them using the following format.
const obj = {
name: 'Joe',
food: 'cake'
}
const { name: myName, food: myFood } = obj;
console.log(myName, myFood);
// 'Joe' 'cake'
In the following example, destructuring is used to cleanly pass the person object to the introduce function. In other words, destructuring can be (and often is) used directly for extracting parameters passed to a function. If you’re familiar with React, you probably have seen this before!
const person = {
name: 'Eddie',
age: 24
}
function introduce({ name, age }) {
console.log(`I'm ${name} and I'm ${age} years old!`);
}
console.log(introduce(person));
// "I'm Eddie and I'm 24 years old!"
3. Closures
Closure is an important JavaScript pattern to give private access to a variable. In this example, createGreeter returns an anonymous function that has access to the supplied greeting, “Hello.” For all future uses, sayHello will have access to this greeting!
function createGreeter(greeting) {
return function(name) {
console.log(greeting + ', ' + name);
}
}
const sayHello = createGreeter('Hello');
sayHello('Joe');
// Hello, Joe
In a more real-world scenario, you could envision an initial function apiConnect(apiKey) that returns some methods that would use the API key. In this case, the apiKey would just need to be provided once and never again.
function apiConnect(apiKey) {
function get(route) {
return fetch(`${route}?key=${apiKey}`);
}
function post(route, params) {
return fetch(route, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Authorization': `Bearer ${apiKey}`
}
})
}
return { get, post }
}
const api = apiConnect('my-secret-key');
// No need to include the apiKey anymore
api.get('http://www.example.com/get-endpoint');
api.post('http://www.example.com/post-endpoint', { name: 'Joe' });
4. Spread Syntax
A JavaScript concept that can throw people off but is relatively simple is the spread operator! In the following case, Math.max can't be applied to the arr array because it doesn't take an array as an argument, it takes the individual elements as arguments. The spread operator ... is used to pull the individual elements out the array.
const arr = [4, 6, -1, 3, 10, 4];
const max = Math.max(...arr);
console.log(max);
// 10
5. Rest Syntax
Let’s talk about JavaScript rest syntax. You can use it to put any number of arguments passed to a function into an array!
function myFunc(...args) {
console.log(args[0] + args[1]);
}
myFunc(1, 2, 3, 4);
// 3
6. Identity Operator (===) vs. Equality Operator (==)
Be sure to know the difference between the identify operator (===) and equality operator (==) in JavaScript! The ==operator will do type conversion prior to comparing values whereas the === operator will not do any type conversion before comparing.
console.log(0 == '0');
// true
console.log(0 === '0');
// false
7. Callback Functions
Far too many people are intimidated by JavaScript callback functions! They are simple, take this example. The console.log function is being passed as a callback to myFunc. It gets executed when setTimeout completes. That’s all there is to it!
function myFunc(text, callback) {
setTimeout(function() {
callback(text);
}, 2000);
}
myFunc('Hello world!', console.log);
// 'Hello world!'
If you didn't know any of these 7 principles before, you've probably improved your JavaScript knowledge! And if you knew them all, hopefully this was an opportunity to put your knowledge to the test.
Top comments (0)