Programming
October 19, 2023
8 min read
Welcome to this beginner JavaScript tutorial! If you're completely new to programming or have no prior experience with JavaScript, then this guide is for you.
JavaScript has grown enormously in popularity and usage since it first appeared in 1995 as a simple scripting language for adding dynamic interactivity to websites. Originally created by Brendan Eich at Netscape, JavaScript now powers far beyond just web pages. Today it is used for full-stack web applications, mobile apps, game development, IoT devices, and more. Its flexibility as a lightweight, interpreted language that can run on both client and server makes JavaScript one of the most widely-used programming languages globally.
Over the course of this hands-on tutorial, you'll learn the core foundations of modern JavaScript (ES6 and beyond) through interactive examples and coding challenges. We'll cover fundamental language features like variables, functions, loops, conditionals, arrays, objects and more. You'll also learn how to manipulate the DOM to create dynamic web pages, handle events like clicks and hovers, validate forms, store data, and build interactive apps right in the browser.
With a focus on practical exercises for cementing each concept, this tutorial will give you a solid JavaScript base to start building your skills. Once you complete this guide, you'll have the knowledge needed to progress to more advanced JavaScript topics and tutorials here on Learn JavaScript. Let's get started!
Here are some key facts about JavaScript:
Today, JavaScript powers full-stack web applications, cross-platform mobile app development with React Native, game development engines like Phaser, server-side programming with Node.js, and even machine learning libraries like TensorFlow.js. Its flexibility and ubiquity make it one of the most widely-used programming languages globally.
This beginner JavaScript tutorial is ideal for:
No prior JavaScript experience is required to follow along! As long as you have an interest in coding and a willingness to learn through hands-on examples, this tutorial will teach you JavaScript fundamentals in a clear, engaging way. Let's get coding!
To start using JavaScript, you first need to learn the building blocks of the language:
<script>
tagsWe'll cover each of these concepts below with beginner-friendly introductions and interactive examples you can code yourself in the browser.
Variables are containers that hold values in JavaScript. You declare a variable with let
, const
or var
:
let myVariable = 'Hello';
JavaScript has several built-in data types like strings, numbers, booleans, etc. You can perform operations on variables using assignment, arithmetic, and string operators:
let x = 5;
let y = 10;
let z = x + y; // 15
To control program flow based on conditions, you use if
, else if
, and else
:
let timeOfDay = 'morning';
if (timeOfDay === 'morning') {
console.log('Good morning!');
} else if (timeOfDay === 'afternoon') {
console.log('Good afternoon!');
} else {
console.log('Good evening!');
}
This if/else statement prints "Good morning!" if timeOfDay equals "morning".
And loops allow you to repeat tasks efficiently:
for (let i = 0; i < 5; i++) {
console.log(i); // Prints 0, 1, 2, 3, 4
}
That covers some key language fundamentals! Now let's look at functions...
Functions are reusable blocks of code that perform specific tasks:
function greetUser() {
console.log('Hello!');
}
greetUser(); // Prints "Hello!"
You can pass data into functions as parameters, and return values from them:
function double(x) {
return x * 2;
}
let num = double(5); // num = 10
This is just a sample of the core concepts we'll cover. You'll learn by coding each one in real interactive examples!
When a web page loads, the browser creates a DOM (Document Object Model) representing the page structure as nodes and objects.
JavaScript can access and manipulate the DOM to dynamically change web pages. For example:
Here's a taste of DOM manipulation with JavaScript:
Get a button by its ID:
const button = document.getElementById('myButton');
Change its text:
button.textContent = 'Click Me!';
Change CSS properties:
button.style.backgroundColor = 'blue';
This allows you to update UI elements, values, styles and more.
Elements are structured in a tree with parent, child and sibling relationships.
Get the first child element:
const firstChild = parent.firstElementChild;
Append a new child element:
parent.appendChild(newElement);
You'll learn more DOM manipulation by actually coding examples!
Events are actions that occur on a webpage like mouse clicks, hovers, key presses, and scrolling.
With JavaScript, you can detect events and run code in response using event handlers:
button.addEventListener('click', handleClick);
function handleClick() {
// Do something on click
}
Some common events you'll use:
click
- Mouse click on an elementinput
- Value changed on form fieldssubmit
- Form submittedkeypress
- Key pressed on keyboardscroll
- User scrolled pageHere are some key concepts around handling events with JavaScript:
Detect clicks with onclick
attribute handlers:
<button onclick="handleClick()">Click</button>
Or use addEventListener()
in JS:
button.addEventListener('click', handleClick);
The handleClick
function runs on click!
Stop event propagation with event.stopPropagation()
:
function handleClick(event) {
event.stopPropagation();
// Prevents event from bubbling
}
This gives you fine-grained control over event behavior.
Validate forms before submission:
form.addEventListener('submit', validate);
function validate(event) {
if(username.value === '') {
alert('Please enter a username');
event.preventDefault(); // Stop form submit
}
// Check other inputs
}
You can make live forms that provide real-time user feedback!
And there's a lot more to explore with events. You'll get hands-on experience with interactive examples.
Once you have a good grasp of the core concepts, it's time to put your skills to work building real applications and components with JavaScript. Here are some ideas:
Use DOM methods like getElementById()
to select elements.
Attach click handlers to number buttons:
button.addEventListener('click', handleNumber);
function handleNumber() {
// Concatenate button value to output
}
Write a calculate()
function to compute the result when operators like +
, -
are clicked.
Clear the output when a "C" (clear) button is clicked.
With these basics, you can build your own functional calculator entirely in JavaScript!
Use a form to get new todo items from the user.
Append new items to the DOM list:
const newTodo = document.createElement('li');
todosList.appendChild(newTodo);
Save todos array to localStorage
:
localStorage.setItem('todos', JSON.stringify(todos));
Load on page refresh:
const storedTodos = JSON.parse(localStorage.getItem('todos'));
Check off completed, delete items, etc!
This combines many core skills into a complete todo list app.
These examples demonstrate how you can apply your new JavaScript skills to build interactive apps and components. Let's recap what you learned.
In this beginner JavaScript tutorial, you learned the foundations of the language:
You now have fundamental JavaScript skills to add interactivity to sites.
To take your learning further, Learn JavaScript offers advanced tutorials on topics like:
With continued practice and the right resources, you'll master JavaScript in no time!