Learn JavaScript Fundamentals for Beginners in 2023
Introduction to JavaScript Fundamentals
Learning JavaScript can seem daunting as a beginner. But mastering the fundamentals opens endless possibilities.
In this comprehensive guide, you'll learn:
Core concepts like variables, functions, scope, objects, arrays
How JavaScript is executed and processed
Common errors and debugging tips
Real-world code examples for each topic
Exercises to apply what you learn
You’ll gain a deep understanding of JavaScript's building blocks, preparing you to create websites, apps, games - anything you can dream up!
Let's start from square one and master the basics. The JavaScript universe awaits...
Setting Up a Development Environment
Before diving in, you'll need an environment to run JavaScript code. Here are a few options:
Codepen
Codepen is a free online code editor where you can write and execute JS in the browser. No installation is needed!
Local Text Editor + Browser
Alternatively, use a text editor like VS Code or Sublime Text to create .js files. Open the files in your browser to run the code.
Node.js
For running JavaScript outside the browser, install Node.js. It comes with the node command to execute .js files.
That covers the development basics - let's move on to learning JavaScript!
Storing Data with Variables
Variables allow storing data to be used in your code.
To declare a variable, use let
or const
:
let name = 'Bob';
const age = 30;
This creates variables called name
and age
.
Naming conventions: use camelCase and descriptive names:
let studentName = 'Bob';
const classSize = 40;
TIP: Avoid single letters like a
or shortened names without meaning.
You can store any data type in a variable:
let students = ['John', 'Sarah', 'Steve']; // Array
let user = {name: 'Jack', age: 20}; // Object
let isAdmin = false; // Boolean
Variables should be declared before use to avoid issues:
✅ GOOD
let score;
score = 10;
❌ BAD
score = 10; // Undeclared!
Common mistakes are using var
instead of let
/const
or forgetting to declare variables altogether.
So remember to always declare with let
and const
!
Exercise
Create variables to store your:
Name
Age
Favorite food
Log them to the console.
Working with Functions
Functions allow reusable code:
function greetUser() {
console.log('Hello!');
}
greetUser();
greetUser();
The function is defined once and then can be executed by calling it.
Function anatomy:
function functionName(parameters) {
// Code to run
return returnValue;
}
functionName
- a name that describes the taskparameters
- values passed into the functionreturnValue
- value returned back
For example, a function to add numbers:
function add(a, b) {
return a + b;
}
add(2, 3); // Returns 5
We call add()
passing arguments 2 and 3, which are assigned to parameters a
and b
.
Functions are fundamental in JavaScript - they:
Reduce duplication
Split complex tasks
Encapsulate logic
With practice, you'll be a functions pro!
Exercise
Write a function greet
that takes a name and returns a greeting.
Making Decisions with Conditionals
Often, we want to run different code based on certain conditions:
let hour = 10;
if (hour < 12) {
console.log('Good morning!'); // Runs if condition is true
}
Common operators:
<
Less than<=
Less than or equal>
Greater than>=
Greater than or equal===
Strict equality!==
Strict inequality
We can add an else
clause:
if (hour < 12) {
console.log('Good morning!');
} else {
console.log('Good afternoon!');
}
And else if
:
if (hour < 12) {
console.log('Good morning!');
} else if (hour < 17) {
console.log('Good afternoon!');
} else {
console.log('Good evening!');
}
Logical operators like AND (&&)
and OR (||)
combine conditions:
if (hour < 12 && isWeekday) {
console.log('It's a weekday morning!');
}
Don't forget curly braces {}
and parentheses ()
!
Exercise
Write an if
statement that checks if num
is odd or even.
Repeating Code with Loops
Loops repeat code until a condition is met:
for (let i = 0; i < 5; i++) {
// Executes 5 times
}
A for
loop has 3 parts:
Initializer -
let i = 0
- Run once before loopCondition check -
i < 5
- Checked each iterationIncrement -
i++
- Runs each loop iteration
While loops repeat while a condition is true:
let i = 0;
while (i < 5) {
// Executes 5 times
i++;
}
And for-of loops iterate arrays:
let colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
// Logs each color
Loops are essential for repeating tasks efficiently.
Exercise
Write a loop that logs the numbers 1 to 20.
Arrays to Store Data
Arrays store ordered, indexed data:
let fruits = ['Apple', 'Banana', 'Orange'];
Elements are accessed by index:
let firstFruit = fruits[0]; // 'Apple'
Arrays have tons of built-in functionality, like .push()
:
fruits.push('Strawberry'); // Appends new item
And .length
:
fruits.length; // 4
Arrays can hold any data type:
let mixed = [1, 'Hello', true, null];
And nest arrays within arrays:
let matrix = [
[1, 2, 3],
[4, 5, 6]
];
Use arrays whenever working with ordered data sets.
Exercise
Given the array const words = ['hello', 'world']
, log the string 'hello world' using array indexing.
Objects for Organized Data
Objects store key-value data:
let user = {
name: 'John',
age: 30,
email: 'john@example.com'
};
Access values using dot notation:
user.name; // 'John'
Or brackets:
user['email']; // 'john@example.com'
Object keys should use camelCase:
let person = {
firstName: 'Jake',
lastName: 'Paul'
};
Objects hold unordered data of any type. They provide great data modeling capability.
Exercise
Given a user object, log the user's full name to the console.
Scope and Closure
Scope determines where variables are accessible.
Global scope
Globals are accessible everywhere:
let name = 'John'; // Global variable
function sayHi() {
console.log(`Hi ${name}!`); // Uses global variable
}
Local scope
Variables in functions can't be accessed externally:
function calcArea() {
let width = 30; // Local variable
return width * 100;
}
console.log(width); // Error!
Inner scopes can access outer scopes:
let powerLevel = 9001;
function fight() {
let strength = powerLevel; // Can access powerLevel
console.log(strength);
}
This nested accessibility is called closure.
Exercise
Identify which variables are locally scoped versus globally scoped.
Putting It All Together
Let's combine what you've learned to create an interactive game!
The game will:
Generate a random number
Prompt the player to guess the number
Indicate if the guess is too low or high
Congratulate the player if they guess correctly
Here's one way to implement it:
// Generate random number between 1 and 10
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guess = prompt('Guess a number between 1 and 10'); // Prompt guess
// Convert string to number
guess = Number(guess);
// Check if guess is correct
if (guess === randomNumber) {
console.log('Congratulations, you guessed the number!');
} else if (guess < randomNumber) {
console.log('Too low! Guess again!');
} else {
console.log('Too high! Guess again!');
}
This combines user input, control flow, operations, and more. With some extra polish, we could turn it into a full-fledged game!
Next Steps
You did it! You now grasp the JavaScript fundamentals - great job.
Here are some next topics to master:
Intermediate and advanced JavaScript programming
Complex data structures like stacks, queues, linked lists
Algorithms and problem-solving
ES6+ modern JavaScript syntax
DOM manipulation for web development
Node.js for server-side programming
Learning never stops in programming. Take it one step at a time, internalize the foundations, and you'll be an expert coder before you know it!
What JavaScript concept are you most excited to learn next? Let me know in the comments!
Subscribe to my newsletter
Read articles from Mikey directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Mikey
Mikey
Undergrad Student in domain of Web developer at Chandigarh University.