Hello there! If you're just starting your JavaScript journey, or simply want to refresh your foundational knowledge, you've come to the right place. JavaScript is an incredibly interesting and powerful language, but to master it, we need to understand the most basic rules.
Let's forget about dry and complex definitions. In this article, we'll explore the core rules of JavaScript in a simple, approachable, and easy-to-understand way. Think of it as if we're sitting at a coffee shop chatting about code. Let's get started! ☕
1. Variables and Constants: "Boxes" to Store Data
Imagine you have boxes to store things. In JavaScript, variables and constants work similarly - they're used to store information.
Variables (var
, let
): Like a box where you can change what's inside. You can assign a value to it, and then change that value anytime you want.
let name = 'Seven'
name = 'Eight' // Okay, no problem
- Tip: Nowadays, prefer using
let
instead ofvar
.let
has clearer rules and helps you avoid many unnecessary errors.
Constants (const
): This is a "sealed" box. Once you put something in, you can't change it anymore.
const PI = 3.14
PI = 3.15 // Error immediately!
- When to use? Whenever you're certain that a value won't change, use
const
. This makes your code safer and easier to understand.
Rules to remember:
- Variable names must be meaningful (e.g.,
userName
instead ofx
). - Variable names can start with letters, underscore
_
, or dollar sign$
. - JavaScript is case-sensitive (
userName
is different fromusername
).
2. Data Types: The "Ingredients" of Your Program
JavaScript has several basic data types that you'll work with daily.
String: Anything enclosed in single quotes ' '
, double quotes " "
, or backticks ` `
. Used to represent text.
let greeting = 'Hello everyone!'
Number: Includes both integers and decimals.
let age = 25
let price = 19.99
Boolean: Only has two values: true
or false
. Often used for condition checking.
let isLoggedIn = true
Null: Represents "empty" or "no value" intentionally. Like deliberately leaving a box empty.
let car = null
Undefined: Means a variable has been declared but not assigned a value. The box has a name but nothing has been put in it yet.
let myVar // myVar is now undefined
Object: A more complex data type that allows you to store a collection of key: value
pairs. Think of it as a cabinet with multiple drawers, each with a label and containing different items.
let person = { name: 'An', age: 30 }
Array: A special type of object used to store a list of values.
let fruits = ['Apple', 'Orange', 'Mango']
3. Operators: "Tools" for Data Processing
Operators help you perform calculations and comparisons.
Arithmetic operators: +
, -
, *
, /
, %
(modulo).
let total = 10 + 5
Assignment operators: =
, +=
, -=
.
let score = 10
score += 5 // Equivalent to score = score + 5;
Comparison operators: ==
(loose equality, compares only values), ===
(strict equality, compares both value and data type), !=
, !==
, >
, <
, >=
, <=
.
'5' == 5 // true
'5' === 5 // false (because one is string, one is number)
- Tip: Always prefer using
===
and!==
to avoid unpredictable results.
Logical operators: &&
(AND), ||
(OR), !
(NOT).
if (age > 18 && hasLicense) { ... }
4. Control Structures: "Road Signs" Guiding Program Flow
Code doesn't always run from top to bottom. Control structures help your program make decisions and repeat actions.
If...Else: Used to execute a block of code if a condition is true, and another block if the condition is false.
let hour = 14
if (hour < 12) {
console.log('Good morning!')
} else {
console.log('Good afternoon!')
}
Switch...Case: Used when you have multiple conditions to check with the same variable. It's cleaner than using multiple if...else if
.
let fruit = 'Apple'
switch (fruit) {
case 'Banana':
console.log('Banana price is $0.50/kg.')
break
case 'Apple':
console.log('Apple price is $1.20/kg.')
break
default:
console.log("Sorry, we're out of stock.")
}
Loops (For, While): Used to repeat a task.
- For loop: When you know exactly how many times to repeat.
// Print numbers from 0 to 4
for (let i = 0; i < 5; i++) {
console.log(i)
}
- While loop: When you want to loop until a certain condition is no longer true.
let i = 0
while (i < 5) {
console.log(i)
i++
}
5. Functions: "Machines" for Reusability
A function is a named block of code that you can call to execute anytime you want. This helps you avoid repeating code and makes your program more organized.
// Declare function
function greet(name) {
console.log('Hello, ' + name + '!')
}
// Call function to use it
greet('Minh') // Result: Hello, Minh!
greet('Hoa') // Result: Hello, Hoa!
Arrow Function (ES6): This is a more concise way to write functions, very popular nowadays.
const add = (a, b) => {
return a + b
}
// Or even shorter if the function only has one return line
const subtract = (a, b) => a - b
console.log(add(5, 3)) // 8
console.log(subtract(10, 4)) // 6
These are the most fundamental and core rules of JavaScript. They're like the alphabet and grammar you need to master before writing amazing stories with code.
Don't try to memorize everything. The best way to remember is to practice, practice, and practice. Open your browser, open the console (press F12), and try typing each command. Write small scripts, solve simple problems.
The journey of learning programming is a marathon, not a sprint. Be patient, be curious, and don't be afraid to make mistakes.
Wish you happy and efficient coding hours! ✨