JavaScript is the language that makes web pages interactive, and one of the best first programming languages to learn. This course teaches the core ideas: values, variables, decisions, loops, functions, arrays, objects and working with the page.
Lessons are deliberately small. Read one, run its examples in your browser console or a scratch file, then change them until you can predict what the code will do before you run it.
1. What is JavaScript? (start here)
The programming language that makes web pages do things.
So far on the web you have met two languages: HTML (what is on the page) and CSS (how it looks). Neither can think. They cannot add two numbers, check whether a password is long enough, or react when someone clicks. That is the job of JavaScript.
JavaScript is a programming language. A programming language is a way of giving a computer precise instructions, one after another, in text. The computer follows them exactly, very fast, without getting bored.
What JavaScript is used for
- Making web pages interactive: buttons, menus, games, live chat, maps.
- Checking forms and showing messages.
- Running on servers too (with a tool called Node.js), so one language can build a whole app.
- Phone apps, desktop apps and much more.
It is one of the most widely used languages in the world, and it runs in every web browser, so you can start with nothing installed.
JavaScript is not Java
The names sound alike, but Java and JavaScript are different languages made for different jobs. The name was a marketing choice from the 1990s. Do not mix them up.
What a program is
A program is a list of instructions. Think of a recipe: "boil water, add pasta, wait 10 minutes". A computer program is like that, except the instructions are written in a language the computer understands, and the computer does exactly what you wrote, even if it is wrong.
console.log("Step 1");
console.log("Step 2");
console.log("Step 3");A tiny program: three instructions, run from top to bottom
The computer reads from the top to the bottom, one line at a time. If you swap the lines, the output swaps too.
- JavaScript is a programming language that gives web pages behaviour.
- A program is a list of instructions the computer runs from top to bottom.
- JavaScript and Java are different languages.
2. Where your code runs
How to see what your program does.
In this club you write JavaScript in the Playground. You type code, press Run, and the result appears in the Output box. There is nothing to install.
Where else does JavaScript run?
- In your browser. Press F12 (or right-click a page and choose Inspect), open the Console tab, and you can type JavaScript right there.
- In a web page. HTML can include JavaScript with a
<script>element. - On a computer with Node.js, outside the browser entirely.
<script>
console.log("Hello from the page!");
</script>JavaScript inside an HTML page
Output and the console
Most beginner programs show their results with console.log(...). It prints a value on a new line in the console, a text window meant for developers. In this club the Output box is the console.
What happens when you make a mistake
You will make mistakes. Everybody does, every day. When code is broken, JavaScript stops and shows an error message, for example:
ReferenceError: nme is not definedA typical error
Read it like a clue. ReferenceError is the kind of error. nme is not defined says you used a name (nme) that does not exist. Maybe you meant name. Error messages are your friends: they say what went wrong, and often exactly where.
- Code runs in the Playground, a browser's console, a web page, or Node.js.
- console.log shows values in the output.
- Error messages tell you what went wrong; read them carefully.
3. Your first program: console.log
Saying hello to the computer.
Time to write real code. A statement is one instruction. The simplest useful statement shows something on the screen:
console.log("Hello, club!");Show a message
Let us read it piece by piece:
console.logis a built-in tool: it prints something.- The parentheses
( )hold what you want to print. Whatever is inside is called the argument. "Hello, club!"is a string: text between quotes.- The semicolon
;ends the statement, like a full stop.
Printing more than one thing
You can print several values in one call, separated by commas.
console.log("Score:", 42);
console.log(1 + 2);Several values in one go
The second line prints 3. Anything that is not in quotes is treated as code that JavaScript works out first.
Comments
Text after // is a comment. The computer ignores it. Use comments to explain your code to future you.
// This line prints a greeting
console.log("Hello!"); // this part is also a commentComments do nothing, but they help people
Common beginner mistakes
- Forgetting the quotes:
console.log(Hello)looks for something calledHelloand fails. Text needs quotes. - Mismatched quotes:
"Hello'starts with a double quote and ends with a single one. - Wrong capitals:
Console.logorconsole.Logwill not work. JavaScript is case-sensitive. - Forgetting a closing bracket
).
Try it
Print anything at all with console.log, run it, and the first challenge is done.
- A statement is one instruction. End it with a semicolon.
- console.log(value) prints a value.
- Text goes in quotes. // starts a comment. Capital letters matter.
4. Variables: giving names to values
Boxes with labels that remember things.
Programs need to remember things: a score, a name, a total. A variable is a named container for a value. You pick the name, store a value in it, and use the name later instead of the value.
const name = "Sam";
let score = 0;
score = score + 10;
console.log(name, score);Creating and using variables
Declaring a variable
constcreates a name whose value cannot be replaced. Use it by default.letcreates a name whose value can change later. Use it when the value will change, like a score.=is assignment, not "equals" like in maths. It means "store the value on the right into the name on the left".
const age = 20;
age = 21; // Error: Assignment to constant variable.What happens with const
Reading the example
let score = 0; creates a variable called score with the value 0. Then score = score + 10; means: take the current value of score (0), add 10, and store the result (10) back in score. The next line prints Sam 10.
Naming rules
- Use letters, digits,
_and$. Names cannot start with a digit. - Names are case-sensitive:
scoreandScoreare two different variables. - Write names in camelCase:
playerScore,totalPrice. The first word is lowercase, and each later word starts with a capital. - Choose names that say what the value is.
priceis better thanp.
var. It is the old way to make variables and it has confusing rules. In new code, use const and let.- A variable is a named container for a value.
- Use const by default, let when the value changes.
- = means "store", not "equals". Use camelCase and meaningful names.
5. Types of values
Numbers, text and true or false.
Every value in JavaScript has a type, which says what kind of thing it is and what you can do with it. Three types come first.
Number
Whole numbers and decimals, with no quotes: 42, 3.14, -7.
String
Text, always in quotes (single '...', double "...", or backticks).
Boolean
Only two possible values: true or false. They answer yes/no questions: "is the user logged in?"
console.log(42);
console.log("forty-two");
console.log(true);One of each
Why types matter
2 + 3 gives 5 because both are numbers. But "2" + "3" gives "23": with strings, + glues text together.
console.log(2 + 3);
console.log("2" + "3");Same symbol, different result
A number in quotes is not a number. It is text that looks like one.
Checking a type
typeof tells you the type of a value.
console.log(typeof 42);
console.log(typeof "hello");
console.log(typeof true);typeof in action
This prints number, string and boolean.
Two special values
undefinedmeans "no value has been given yet".nullmeans "deliberately empty".
let nothingYet;
console.log(nothingYet);undefined appears when you have not stored anything
Your challenge
Print a number and a boolean so the output shows a number and true or false.
- Three main types: number, string, boolean.
- Quotes make text. A number in quotes is a string.
- typeof shows a value's type. undefined means no value yet.
6. Operators: calculating and comparing
The symbols that do the work.
An operator is a symbol that does something with values.
Arithmetic
console.log(7 + 2); // addition: 9
console.log(7 - 2); // subtraction: 5
console.log(7 * 2); // multiplication: 14
console.log(7 / 2); // division: 3.5
console.log(7 % 2); // remainder: 1Maths
% is the remainder operator. 7 % 2 is 1 because 2 goes into 7 three times with 1 left over. It is a very useful trick: a number is even if n % 2 is 0.
Comparison
Comparison operators give back a boolean (true or false).
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 === 5); // true: equal
console.log(5 !== 4); // true: not equalComparisons
Always use === (three equals signs) to check for equality, not ==. The three-sign version compares the value and the type, which avoids surprises. A single = is assignment, a very common slip!
Logical operators
They combine booleans.
&&means and: both must be true.||means or: at least one must be true.!means not: flips true to false.
const age = 20;
console.log(age >= 18 && age < 65);
console.log(!(age > 30));Combining conditions
Shortcuts
score += 5 means score = score + 5. Likewise -=, *=, and score++ adds 1.
Order of operations
Like in maths, *, /, % happen before + and -. Use parentheses to be clear: (2 + 3) * 4 is 20.
- + - * / do maths. % gives the remainder.
- > < >= <= === !== compare and give true or false.
- && (and), || (or), ! (not) combine booleans. Use === for equality.
7. Functions: reusable instructions
Write once, use many times.
A function is a named, reusable block of code. Instead of writing the same steps again and again, you put them in a function and call it whenever you need them.
Think of a blender. You do not rebuild it every morning. You put things in (the inputs), press the button, and get a smoothie (the output).
function double(n) {
return n * 2;
}
console.log(double(21));
console.log(double(5));Define a function, then call it
The parts
functionis the keyword that starts a definition.doubleis the name you choose.(n)lists the parameters: names for the inputs.nis a placeholder for whatever value is passed in.{ ... }holds the body: the code that runs.returnsends a value back to whoever called the function. The function stops there.
Calling a function
double(21) calls the function. The value 21 is the argument, and it becomes n inside the function. The call itself becomes the returned value, 42, which console.log prints.
Defining is not running
Writing the function does nothing on its own. It only runs when you call it.
Return vs print
console.log shows something to a person. return hands back a value to the code that called the function. For a function like add, you want return: then you can use the answer for more calculation.
function add(a, b) {
return a + b;
}
console.log(add(2, 3) * 10);Using a function's result in another expression
Several parameters
Separate them with commas. The order of the arguments matches the order of the parameters.
return, the function gives back undefined. In your challenge, make sure the answer is returned, not just printed.- A function is a named, reusable block. Parameters are inputs; return is the output.
- Calling a function (name + parentheses) runs it.
- return gives a value back; console.log only shows it.
8. Working with strings
Text and the tools that change it.
A string is a sequence of characters. You can write strings with single quotes, double quotes or backticks. They work the same, apart from a few extras for backticks.
Joining strings
The + operator glues strings together. This is called concatenation.
const name = "Sam";
console.log("Hello, " + name + "!");Joining with +
Watch the space after the comma in "Hello, ". Strings are joined exactly as written, so you have to add the spaces.
Template literals
Backtick strings let you put values inside with ${...}. This is often easier to read.
const name = "Sam";
console.log(`Hello, ${name}!`);The same greeting with a template literal
Useful properties and methods
A method is a function attached to a value, called with a dot.
const word = "club";
console.log(word.length); // 4 (a property: no parentheses)
console.log(word.toUpperCase()); // "CLUB"
console.log(word.toLowerCase()); // "club"
console.log(word.includes("lu")); // true
console.log(word[0]); // "c" (the first character)A tour of string tools
Strings never change
String methods do not modify the original. They return a new string.
const word = "club";
word.toUpperCase(); // result thrown away
console.log(word); // still "club"
console.log(word.toUpperCase());The original stays the same
Your challenge
Write a function greet(name) that returns 'Hello, ' followed by the name and '!'.
- Join strings with + or template literals.
- .length, .toUpperCase(), .includes() and more are string tools.
- Strings are never changed in place; methods return new strings.
9. Making decisions with if
Code that chooses what to do.
So far every line runs. Real programs need to choose: "if it is raining, take an umbrella". In JavaScript that is if.
const n = 7;
if (n % 2 === 0) {
console.log("even");
} else {
console.log("odd");
}if / else
How it reads
- After
if, the condition goes in parentheses. It is something that istrueorfalse. - If it is true, the first block
{ ... }runs. - If not, the
elseblock runs instead.elseis optional.
More than two choices
Chain extra checks with else if. JavaScript tests them from the top and runs the first one that is true.
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("C");
}Grading
Conditions are booleans
Anything that gives true or false works: age >= 18, name === "Sam", isLoggedIn, or combinations with && and ||.
Functions can decide too
An if inside a function can return early.
function isAdult(age) {
if (age >= 18) {
return true;
}
return false;
}
console.log(isAdult(20));Return true or false from a check
That function can be shortened to return age >= 18;, because the comparison already is a boolean.
Your challenge: isEven
An even number leaves no remainder when divided by 2. Combine % with === and return the result.
if (n = 5) (one equals sign) assigns instead of comparing. Use ===.- if (condition) { ... } else { ... } chooses a path.
- else if adds more choices; the first true one runs.
- A comparison already gives a boolean, so you can return it directly.
10. Arrays: lists of values
Keeping many values together.
So far a variable has held one value. An array holds a whole list of values in order. You write it with square brackets, separating items with commas.
const langs = ["HTML", "CSS", "JS"];
console.log(langs);
console.log(langs.length);Create an array
Reading items: indexes
Every item has a position called an index, and indexes start at 0, not 1.
const langs = ["HTML", "CSS", "JS"];
console.log(langs[0]); // "HTML"
console.log(langs[1]); // "CSS"
console.log(langs[2]); // "JS"The first item is at index 0
Changing arrays
.push(item)adds to the end..pop()removes and returns the last item..lengthis how many items there are..includes(item)istrueif the item is in the array..join(", ")glues all items into one string.
const langs = ["HTML", "CSS"];
langs.push("JS");
console.log(langs.length);
console.log(langs.join(", "));
console.log(langs.includes("CSS"));Array tools
An array declared with const can still have items added. const only stops you from replacing the whole array with a different one.
An array can hold anything
Numbers, strings, even other arrays or objects: [1, "two", true].
- An array is an ordered list in square brackets.
- Indexes start at 0. .length counts the items.
- push, pop, includes and join are everyday tools.
11. Loops: doing something many times
Repeat without repeating yourself.
Imagine adding up a list of 1,000 numbers by writing + 1,000 times. A loop repeats a block of code for you.
for...of
for...of runs once for each item of an array.
const nums = [1, 2, 3];
for (const n of nums) {
console.log(n);
}Print every item
On each round, n is the next item: first 1, then 2, then 3. When the items run out, the loop ends.
The accumulator pattern
To add things up, make a variable that holds the running total, and update it inside the loop.
let total = 0;
for (const n of [1, 2, 3, 4]) {
total += n;
}
console.log(total);Add up an array
Trace through it: total starts at 0; after 1 it is 1; after 2 it is 3; after 3 it is 6; after 4 it is 10. This "start, update each time, then use the result" pattern is everywhere in programming.
The classic for loop
When you want to count, use the three-part for:
for (let i = 0; i < 5; i++) {
console.log(i);
}Count from 0 to 4
The parts: let i = 0 runs once at the start, i < 5 is checked before each round, and i++ runs after each round.
while
while repeats as long as a condition is true. Make sure something in the loop eventually makes it false, or it will never stop.
let n = 3;
while (n > 0) {
console.log(n);
n--;
}Count down
Loops inside functions
Wrap the pattern in a function and it becomes reusable: sumAll(numbers) takes any array. Declare total inside the function, so each call starts fresh.
- A loop repeats code. for...of goes through the items of an array.
- The accumulator pattern: start a total, update it in the loop, use it after.
- while repeats until its condition is false; make sure it can become false.
12. Arrays and strings together
Splitting, reversing and joining.
Strings and arrays are close relatives. You can turn a string into an array of pieces, work with the pieces, and turn them back into a string.
split
.split(separator) cuts a string into an array. An empty separator "" splits into single characters.
console.log("a-b-c".split("-"));
console.log("club".split(""));String to array
reverse
.reverse() turns an array around. Note: it changes the array in place.
const nums = [1, 2, 3];
nums.reverse();
console.log(nums);Reverse an array
join
.join(separator) is the opposite of split: it glues the items into a string.
console.log(["c", "l", "u", "b"].join(""));
console.log(["a", "b", "c"].join("-"));Array to string
Chaining
Because each method returns a value, you can call the next one right on it. This is called chaining.
const word = "club";
const backwards = word.split("").reverse().join("");
console.log(backwards);Reverse a word in one line
Read it left to right: split the word into letters, reverse the letters, join them back together. This gives bulc.
Your challenge
Write reverseString(s) that returns the string reversed. Chain the three methods and return the result.
- split turns a string into an array. join turns an array into a string.
- reverse flips an array in place.
- Methods can be chained: s.split("").reverse().join("").
13. Edge cases and the last item
Thinking about "what if it is empty?"
An edge case is an unusual input that can break your code: an empty array, a negative number, a blank string. A professional always asks: what if the input is empty?
Finding the last item
Indexes start at 0, so the first item is array[0]. The last item's index is the length minus one.
const nums = [10, 20, 30];
console.log(nums[0]);
console.log(nums[nums.length - 1]);First and last
nums.length is 3, so nums.length - 1 is 2, which is the index of 30.
What if the array is empty?
For [], the length is 0, so the index is -1. There is no item at -1, and JavaScript quietly gives back undefined. That is a perfectly fine answer to "what is the last item of an empty list?", as long as you meant it.
const empty = [];
console.log(empty[empty.length - 1]);
console.log([1, 2, 3][10]);Reading beyond the array gives undefined
Putting it in a function
function last(array) {
return array[array.length - 1];
}
console.log(last([1, 2, 3]));
console.log(last([]));A function that works for every array
Habits for edge cases
- Test with the normal case, then an empty input, then a single item.
- Think about what the function should return when there is nothing to work with.
- Write down the examples first, then write the code to satisfy them.
- The last index is array.length - 1.
- Reading a missing index gives undefined, not an error.
- Always test with empty and single-item inputs.
14. Arrow functions and callbacks
A shorter way to write small functions.
A function is a value. You can store it in a variable, or pass it into another function. A function passed to another function is called a callback.
Arrow functions
JavaScript has a compact syntax for small functions. The arrow => replaces the function keyword.
function double(n) {
return n * 2;
}
const doubleArrow = (n) => n * 2;
console.log(double(4), doubleArrow(4));The same function, two styles
Reading it: "n goes to n * 2". When the body is a single expression, you can leave out { } and return: the value is returned automatically.
Callbacks
Many array methods take a function and call it for you.
const names = ["Ada", "Sam"];
names.forEach((name) => {
console.log("Hi, " + name);
});forEach calls your function for every item
You will use arrow functions all the time with map, filter and reduce, in the next lessons.
- (x) => x * 2 is a short function. Single expressions return automatically.
- A callback is a function you pass to another function.
15. Transforming arrays with map
Build a new array from an old one.
Often you want a new list where every item is changed: all prices with tax, all names in capitals. map does that in one step.
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
console.log(doubled);
console.log(nums);Double every number
How it works
map takes a function. For every item, it calls the function with that item, and collects the returned values into a new array of the same length. The original array is never changed.
const result = [];
for (const n of nums) {
result.push(n * 2);
}Imagine map as a loop you do not have to write
More examples
const names = ["ada", "sam"];
console.log(names.map((s) => s.toUpperCase()));
console.log(names.map((s) => s.length));Map works with any type
Related tool: filter
filter keeps only the items for which the function returns true.
console.log([1, 2, 3, 4].filter((n) => n % 2 === 0));Keep even numbers
Your challenge
Write doubleAll(numbers) that returns a new array with each number doubled. Do not forget return!
- map returns a new array, same length, with each item transformed.
- filter returns a new array with only the matching items.
- Neither changes the original array.
16. Objects: grouping related values
Name things with properties.
An array is a list in order. An object groups related values under names. Use an object when you describe one thing with several details: a user, a product, a game character.
const user = { name: "Sam", age: 20 };
console.log(user.name);
console.log(user.age);An object with two properties
Parts
- Curly braces
{ }hold the object. - Each entry is a property: a key, a colon, and a value.
- Properties are separated by commas.
- Read a property with a dot:
user.name.
Changing and adding
const user = { name: "Sam", age: 20 };
user.age = 21;
user.city = "Dhaka";
console.log(user);Update and add properties
The short form
When a variable has the same name as the key, you can write it once.
const name = "Ada";
const age = 36;
const person = { name, age };
console.log(person);Shorthand properties
{ name, age } is the same as { name: name, age: age }.
Functions that make objects
function makeProfile(name, age) {
return { name, age };
}
console.log(makeProfile("Ada", 36));Return an object from a function
Objects in arrays
Real data is often a list of objects.
const users = [
{ name: "Ada", age: 36 },
{ name: "Sam", age: 20 },
];
console.log(users.map((u) => u.name));An array of objects
- An object has named properties: { key: value }.
- Read with a dot (user.name); change by assigning.
- Arrays of objects are how most real data is stored.
17. Going further: filter, reduce and find
More array superpowers.
You already know map and filter. Three more tools cover most array work.
find
Returns the first item that matches, or undefined.
const nums = [3, 8, 12, 5];
console.log(nums.find((n) => n > 5));Find the first item matching a test
reduce
Combines all items into one value. It is the accumulator pattern in one call.
const total = [1, 2, 3, 4].reduce((sum, n) => sum + n, 0);
console.log(total);Add everything up
reduce takes a function with two parameters, the running result (sum) and the current item (n), plus a starting value (0).
sort
Sorts an array in place. For numbers, pass a comparison function, otherwise JavaScript sorts as text.
const nums = [10, 2, 33, 4];
nums.sort((a, b) => a - b);
console.log(nums);Numeric sort
Chain them
const result = [1, 2, 3, 4]
.filter((n) => n % 2 === 0)
.map((n) => n * n)
.reduce((sum, n) => sum + n, 0);
console.log(result);Sum of the squares of the even numbers
- find: first match. reduce: many values into one. sort: reorder.
- Chain filter, map and reduce for powerful one-line processing.
18. Scope: where names live
Which code can see which variable.
Scope is the area of code where a name can be used.
function demo() {
const secret = 42;
console.log(secret);
}
demo();A variable inside a function is invisible outside
If you tried console.log(secret) outside the function, you would get ReferenceError: secret is not defined.
Block scope
let and const also stay inside the nearest { }, like the body of an if or a loop.
for (let i = 0; i < 3; i++) {
console.log(i);
}i belongs to the loop only
Why scope is good
It keeps functions independent. A variable inside a function disappears when the function ends, so two functions can both use a name like total without clashing. That is why you create the accumulator inside your function.
Outer variables
Code inside a function can see variables from outside it.
const greeting = "Hello";
function greet(name) {
return greeting + ", " + name;
}
console.log(greet("Sam"));A function reading an outer variable
- Names live in the function or block where they are declared.
- Inner code can read outer variables; outer code cannot read inner ones.
19. Finding bugs
What to do when your code does not work.
A bug is a mistake in code. Finding and fixing bugs (debugging) is a big part of a programmer's day.
Step 1: read the error
The message tells you the type and often the line.
SyntaxError: the code is written wrongly: a missing bracket, quote or comma.ReferenceError: you used a name that does not exist (typo, or wrong scope).TypeError: you used a value in a way its type does not allow, like calling something that is not a function.
Step 2: no error but a wrong answer?
Print the values to see what is really happening.
function add(a, b) {
console.log("a is", a, "b is", b);
return a + b;
}
console.log(add(2, 3));Peek inside your function
Step 3: shrink the problem
Cut away everything unrelated until the bug is tiny, then fix it.
Common mistakes checklist
=instead of===in a condition.- Forgetting
returnin a function. - Off-by-one: indexes start at 0.
- Quotes making a number into a string.
- Using a variable before it exists.
- Read the error: type, message, line.
- console.log values to inspect them.
- Shrink the problem, then check the usual mistakes.
20. What you can do next
From the basics to real projects.
You now know the foundations that every JavaScript program uses: values and types, variables, operators, functions, conditions, loops, arrays, objects, and array methods.
Where JavaScript goes from here
- The DOM: JavaScript can read and change the HTML on a page. That is how buttons come to life.
- Events: running code when users click, type or scroll.
- Fetching data: loading information from other servers.
- Node.js: running JavaScript outside the browser.
const button = document.querySelector("button");
button.addEventListener("click", () => {
alert("You clicked me!");
});A taste of the DOM (works on a real web page, not in this Playground)
How to keep learning
- Build tiny projects: a counter, a to-do list, a quiz.
- Re-do the challenges without the hints.
- Read other people's code and ask what each line does.
- Share what you build on CodelyTeam and ask for feedback.
- You know the core of JavaScript.
- Next: the DOM, events, fetching data, Node.js.
- Build small projects; practice beats reading.