JavaScript Intermediate Summary - Images: Japanese
Hey there, everyone!
This is the wrap-up article for the JavaScript Intermediate course. If there's anything you've forgotten along the way, use this as a quick refresher.
Objects
A JavaScript object is a collection of data where each entry is identified by a custom name — as opposed to an array, which uses numbered indexes. To access a property value, use [] or .. Objects can also be nested (multi-dimensional). Use the literal notation (object literal) style to define objects. Here's a quick example:
var x = {}; // Defined only.
x["hoge"] = 0; // Assign 0 to x["hoge"].
console.log(x["hoge"]); // Outputs 0.
var y = { // Define and assign at the same time.
"hoge": 0,
hoge1: "Hello World" // Property names without spaces or operators don't need quotes.
};
console.log(y.hoge1); // Outputs "Hello World".
More details here
The for...in statement
The for...in statement lets you loop over every property in an object. The basic syntax looks like this:
for(var variable in object){
// code to run
}
The variable receives each property name (key), not the value — so keep that in mind. The order of iteration isn't guaranteed, which means a regular for loop is generally more reliable for ordered processing. Here's an example:
var x = {
"hoge": 0,
"hoge1": 1,
"hoge2": 2
};
for(var elem in x){
console.log(elem); // Outputs 'hoge', 'hoge1', 'hoge2'.
console.log(x[elem]); // Outputs 0, 1, 2.
}
More details here
document.getElementsByTagName()
document.getElementsByTagName() retrieves elements by tag name, document.getElementsByClassName() by class name, and document.getElementsByName() by name attribute. They all work in a similar way. The result is returned as an array-like object, so don't forget to include the index number when accessing individual elements. You can also chain multiple document.getElement~ calls together. That said, when you need to target deeply nested elements, document.querySelector() is usually easier. Here's a sample:
<div id="test">
<p>This element will be selected!</p>
</div>
<p>This one won't be selected!</p>
<script>
var x = document.getElementById("test").getElementsByTagName("p");
for(var i = 0; i < x.length; ++i){
x[i].innerHTML = "Content changed!";
}
</script>
More details here
document.querySelector()
These methods retrieve elements using CSS selectors. Use 'document.querySelector()' for a single element and 'document.querySelectorAll()' for multiple elements. 'document.querySelector()' stops searching as soon as it finds the first match. 'document.querySelectorAll()' returns an array-like object, so watch out for that. These are very convenient to use, though they tend to be slower than the 'getElementById'-style methods. They really shine when you need to pinpoint deeply nested elements. Here's a sample:
<div class="test">This div has class 'test'.</div>
<p>This is a p element!</p>
<p>This is a p element!</p>
<script>
var x = document.querySelector(".test");
var y = document.querySelectorAll("p");
x.innerHTML = "Content changed! (1)";
for(var i = 0; i < y.length; ++i){
y[i].innerHTML = "Content changed! (2)";
}
</script>
More details here
Scope in JavaScript
In JavaScript, variables and objects defined inside a function cannot be accessed from outside it. Variables accessible from anywhere are called global variables (global objects), while those only accessible within the same function are called local variables (local objects). JavaScript only has function scope — there's no block scope. Note that scope rules vary significantly between programming languages. In JavaScript, if you define a variable or object without var, it becomes global.
More details here
setTimeout and setInterval
setTimeout() executes a function after a specified delay, and setInterval() executes a function repeatedly at a specified interval. Time is specified in milliseconds, so keep that in mind. Here's an example of setTimeout():
function hoge(){
alert("3 seconds have passed!");
}
setTimeout(hoge, 3000);
And here's 'setInterval()'. You can stop it using 'clearInterval()', but to do that you need the return value from 'setInterval()' — so be sure to capture it. If you don't, there's no way to stop it.
function hoge(){
console.log("3 seconds have passed!");
}
var setIV = setInterval(hoge, 3000);
function stop_hoge(){
clearInterval(setIV);
console.log("Stopped!");
}
setTimeout(stop_hoge, 5000);
More details here
The return statement
The return statement lets you specify what value a function gives back when it's called, and it also ends the function's execution at that point. You can return objects or the result of an expression. The value you get back from a function call is called the return value. Writing just return; returns undefined, and omitting return entirely also results in undefined. The return statement can only be used inside a function. Also, you cannot put a line break between return and the expression that follows it. Here's a sample:
function hoge(){
return; // Empty return statement.
}
var x = hoge(); // The variable 'x' receives 'undefined' returned by the function 'hoge'.
console.log(x); // Outputs undefined.
More details here
null and undefined
null represents a state where no data exists, and undefined represents an uninitialized state. Both are treated as false.
var x = null; console.log(x); // Outputs null. var y = undefined; console.log(y); // Outputs undefined.
More details here
Hoisting
In JavaScript, declarations are automatically moved to the top of their scope — this is called hoisting. For example, the following code:
var x = 0; // Global variable.
function hoge(){
console.log(x);
// Imagine there's lots of code here.
// ...
// ...
// ...
// ...
// ...
var x = 1;
}
hoge();
behaves the same as this. It's a common source of unexpected bugs, so watch out:
var x = 0; // Global variable.
function hoge(){
var x; // Only the declaration is hoisted. This defines a local variable 'x', so it starts as 'undefined'.
console.log(x); // Outputs undefined (the local 'x').
// Imagine there's lots of code here.
// ...
// ...
// ...
// ...
// ...
x = 1; // Assigns 1 to the local variable 'x'.
}
hoge();
More details here
Anonymous functions
'function(){}' is called an 'anonymous function'. Because hoisting doesn't apply to anonymous functions, defining functions using function expressions (anonymous functions) is the common approach in JavaScript.
var hoge = function(x, y){
console.log(x, y);
};
Anonymous functions are especially useful for one-off functions. Here's an example:
setTimeout(function(){
alert("3 seconds have passed!");
}, 3000);
One thing to watch out for: in JavaScript, starting a line with 'function' makes it a function declaration statement, so the following syntax is a syntax error. If you want to execute an anonymous function immediately, use an immediately invoked function expression (IIFE) instead.
function(){
// This is not valid.
}
More details here
Immediately Invoked Function Expressions (IIFEs)
An 'IIFE' (Immediately Invoked Function Expression) is an anonymous function that runs right away. In JavaScript, wrapping an anonymous function in '()' prevents it from being interpreted as a function declaration, which is the trick that makes an IIFE work. Here's the basic structure:
(function(){
// code to run
})();
To pass arguments into the anonymous function, do it like this:
var x = 0; // This is the global variable 'x'.
(function(x){ // Receives the value of the global 'x' (which is 0) as the parameter 'x'.
++x; // Adds 1 to the parameter 'x'.
console.log(x); // Outputs 1.
})(x); // Passes the global variable 'x'. At this point, 'x' is 0.
console.log(x); // The 'x' incremented inside the IIFE is the parameter, not the global. So the global 'x' is still 0.
More details here
Pass by reference
In JavaScript, assigning a primitive value copies the value itself (pass by value), but assigning an object copies only a reference to it (pass by reference). So when working with arrays and objects, be mindful of what's happening behind the scenes. A purely nested array can be duplicated, but fully cloning an object is not possible in JavaScript. It's safest to think of objects as something that generally cannot be copied.
More details here
And that wraps up the JavaScript Intermediate course! This section covered a lot of JavaScript's behind-the-scenes behavior, which can be a lot to take in.
Thanks so much for reading all the way through. I hope what you've learned here stays with you as useful knowledge. Until next time!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him. |
If you find any errors or copyright issues, please contact us.