When you are new to JavaScript, the language can feel unpredictable and full of surprises. Here are ten truths that will help you get a handle on the basics and avoid the most common mistakes.
1. JavaScript Runs in the Browser
Explanation:
JavaScript code is executed by your web browser. You do not need to install extra programs or tools. You can write and test JavaScript right inside the browser's developer console.
Example:
console.log("Hello from JavaScript");
Open your browser, press F12, go to the Console tab, and enter the line above to see the result. After you run this code, you will see "Hello from JavaScript" printed in the console.
2. Variables Can Change Type (Dynamic Typing and Type Coercion)
Explanation:
A variable is a container for a value. In JavaScript, a variable can hold any kind of value at any time. JavaScript will also automatically convert between types when you combine them, sometimes in ways that are not obvious.
Example:
let value = 7; // value is a number value = "seven"; // now value is a string let result = "7" + 2; // result is "72" because "7" is a string
After the script runs, result
will be the string "72".
Be aware that mixing types can produce unexpected results.
3. The DOM (Document Object Model)
Explanation:
The Document Object Model, or DOM, is how the browser represents everything on a web page as a tree of objects. JavaScript is used to interact with these objects to read, change, or add content on the page.
Example: We are targeting the paragraph with the ID "message" and changing its text content using JavaScript. <p id="message">Original</p>
<script> document.getElementById("message").innerText = "Updated by JavaScript"; </script>
After this script has run, the paragraph will display "Updated by JavaScript".
4. Event Listeners
Explanation:
Events are user actions like clicking a button, typing on the keyboard, or moving the mouse. An event listener is a piece of code that waits for a certain event, then runs your function.
Example: We are adding a click event listener to a button that shows an alert when clicked. <button id="greetBtn">Greet</button>
<script>
document.getElementById("greetBtn").addEventListener("click", function() {
alert("Hello, user");
});
</script>
After the script runs, clicking the button will show an alert saying "Hello, user".
5. console.log Helps You See What Is Happening
Explanation:
You can use console.log()
to print out messages or values at any point in your code. This is the fastest way to check if your code is working as you expect, or to find where it is going wrong.
Example:
let x = 12; console.log("Current value of x is", x);
The result will be printed in the console: "Current value of x is 12".
6. Scope and Hoisting
Explanation:
- Scope: Where in your code a variable can be accessed. Variables declared inside a function are only available within that function.
- Hoisting: JavaScript moves declarations (but not assignments) to the top of their scope before it runs the code. This means you can sometimes use a variable before it is declared, but the value will be undefined.
Example:
function example() {
console.log(a); // undefined, does not throw an error
var a = 10;
}
example();
You will see "undefined" printed in the console because a
is hoisted but not yet assigned a value when the console.log runs. You can fix this by declaring a
before using it, or by using let
or const
which do not hoist in the same way.
So you see the order of declaring a variable and then trying to use it matters in JavaScript.
7. Asynchronous Code
Explanation:
Some actions, such as loading data from the web or waiting for a timer, do not complete instantly. JavaScript uses asynchronous code to handle these. You will see this with functions like setTimeout
, as well as with Promises and async/await
.
Example:
console.log("Start");
setTimeout(function() {
console.log("This prints after 1 second");
}, 1000);
console.log("End");
// Output will be: Start, End, This prints after 1 second
The script will result in "Start" being printed first, then "End", and finally after 1 second, "This prints after 1 second" will appear. This shows how JavaScript can continue running while waiting for something else to finish. Real-World Example: Imagine you are building a website where someone clicks a button to load the latest weather information. Fetching this data from the internet might take a second or two. If JavaScript waited for the network request to finish before doing anything else, your whole site would freeze until the weather data arrived.
With asynchronous code, you can show a loading spinner right away, keep the site interactive, and only update the weather when the data is ready:
console.log("User clicked button");
showLoadingSpinner();
fetch("https://api.weather.com/latest")
.then(response => response.json())
.then(data => {
updateWeatherWidget(data);
hideLoadingSpinner();
});
console.log("Site stays responsive");
In this example, the weather data loads in the background while your app stays fast and usable. Asynchronous code is what makes this possible.
8. Arrays and Objects Are Core Data Structures
Explanation:
- Array: An ordered list of values.
- Object: A collection of named values (properties).
Examples:
let fruits = ["apple", "banana", "cherry"]; let book = { title: "JavaScript Basics", pages: 200 }; console.log(fruits[0]); // "apple" console.log(book.title); // "JavaScript Basics"
This script being run will print "apple" and "JavaScript Basics" to the console. Arrays and objects are fundamental to organizing data in JavaScript, and you will use them frequently. The main difference is that arrays are ordered and accessed by index, while objects are unordered and accessed by key.
9. Functions Organize Your Code
Explanation:
A function is a named block of code that performs a task. You can call a function as many times as you like, with different inputs.
Example:
function multiply(a, b) {
return a * b;
}
let result = multiply(3, 4); // result is 12
This script defines a function called multiply
that takes two numbers and returns their product. When you call multiply(3, 4)
, it returns 12, which is stored in the variable result
. Functions help you avoid repeating code and make your scripts easier to read.
You can then call this function with different values to get different results, like multiply(5, 6)
which would return 30.
10. Strict Mode Makes JavaScript Safer
Explanation:
If you add the line "use strict";
at the top of your code or function, JavaScript will catch certain mistakes and stop them from silently failing.
Example:
"use strict"; test = 5; // This will throw an error because test is not declared with let or var
This will result in an error saying "test is not defined" because you are trying to assign a value to a variable that has not been declared. Using strict mode helps you catch common errors early and write cleaner code. When to use strict mode? Mostly when you are writing new code or working on a project where you want to enforce better coding practices. It is a good habit to use strict mode in all your JavaScript files. You just have to use it once at the top of your script or function.
Final Thought:
You do not need to know everything before you start building. Learn these ten truths and you will be able to make real progress without falling into JavaScript's most common traps.
That is vibecoding.