0% found this document useful (0 votes)
18 views15 pages

JS Fundamentals

This document is a beginner's guide to JavaScript fundamentals, covering essential topics such as variables, functions, arrays, objects, async/await, and modules. It provides step-by-step instructions for setting up a JavaScript environment, creating files, and writing code, along with practical examples and real-life applications. Additionally, it introduces Node.js for running JavaScript outside the browser and using npm for package management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views15 pages

JS Fundamentals

This document is a beginner's guide to JavaScript fundamentals, covering essential topics such as variables, functions, arrays, objects, async/await, and modules. It provides step-by-step instructions for setting up a JavaScript environment, creating files, and writing code, along with practical examples and real-life applications. Additionally, it introduces Node.js for running JavaScript outside the browser and using npm for package management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

JavaScript Fundamentals: A Beginner's Guide (1-2

Weeks)
Welcome to the wonderful world of JavaScript! Think of JavaScript as the magic that makes
websites come alive - like adding colors to a coloring book or making toys move and dance.

Table of Contents
1. Getting Started
2. Variables - Your Data Containers
3. Functions - Your Helper Friends
4. Arrays - Your Toy Boxes
5. Objects - Your Treasure Chests
6. Async/Await - Waiting Patiently
7. Modules - Sharing Your Toys
8. Node.js Basics - JavaScript Outside the Browser
9. Resources for Further Learning

Getting Started

What You Need


Before we start our JavaScript adventure, let's gather our tools:
1. A Computer - Like having a playground to build in
2. A Text Editor - We recommend Visual Studio Code (it's free!)
3. A Web Browser - Chrome, Firefox, or Safari work great
4. Node.js - We'll install this later for the Node.js section

Setting Up Your First JavaScript File


Step 1: Create a folder

mkdir my-javascript-learning
cd my-javascript-learning

Step 2: Create your first HTML file


Create a file called index.html:
<!DOCTYPE html>
<html>
<head>
<title>My JavaScript Learning</title>
</head>
<body>
<h1>Hello, JavaScript World!</h1>
<script src="script.js"></script>
</body>
</html>

Step 3: Create your JavaScript file


Create a file called script.js:

console.log("Hello, World!");

Step 4: Open in browser


Double-click your index.html file to open it in your browser, then press F12 to see the console
where your message will appear!

Variables - Your Data Containers


Think of variables like different types of containers in your room:

Types of Containers (Variable Declarations)

// let - like a toy box you can change what's inside


let myToyBox = "teddy bear";
myToyBox = "robot"; // You can change it!

// const - like a treasure chest that stays locked


const myTreasure = "golden coin";
// myTreasure = "silver coin"; // This won't work!

// var - like an old container (we don't use this much anymore)
var oldContainer = "old stuff";

Different Types of Things to Store

// Numbers - like counting your toys


let numberOfToys = 5;
let price = 12.99;

// Text (Strings) - like name tags


let myName = "Alex";
let favoriteColor = "blue";

// True or False (Booleans) - like yes/no questions


let isHappy = true;
let isRaining = false;
// Nothing (null and undefined)
let emptyBox = null;
let forgottenToy; // This is undefined

Fun Example: Pet Store

let petName = "Fluffy";


let petAge = 3;
let isPetHungry = true;

console.log("My pet " + petName + " is " + petAge + " years old");
console.log(`My pet ${petName} is ${petAge} years old`); // This is called template liter

Functions - Your Helper Friends


Functions are like having helpful friends who can do specific jobs for you!

Creating Your Helper Friend

// Basic function - like teaching a friend a new trick


function sayHello() {
console.log("Hello there!");
}

// Call your friend to do the trick


sayHello(); // Prints: Hello there!

Functions That Take Instructions

// Function with parameters - like giving your friend specific instructions


function greetPerson(name) {
console.log("Hello, " + name + "!");
}

greetPerson("Sarah"); // Prints: Hello, Sarah!


greetPerson("Tom"); // Prints: Hello, Tom!

Functions That Give You Something Back

// Function that returns something - like asking a friend to bring you something
function addTwoNumbers(first, second) {
return first + second;
}

let result = addTwoNumbers(5, 3);


console.log(result); // Prints: 8
Modern Way: Arrow Functions

// Arrow functions - a shorter way to write functions


const multiply = (a, b) => {
return a * b;
};

// Even shorter for simple functions


const square = (x) => x * x;

console.log(square(4)); // Prints: 16

Real Example: Pizza Calculator

function calculatePizzaSlices(numberOfPeople, slicesPerPerson = 2) {


return numberOfPeople * slicesPerPerson;
}

let partySize = 6;
let totalSlices = calculatePizzaSlices(partySize);
console.log(`We need ${totalSlices} pizza slices for the party!`);

Arrays - Your Toy Boxes


Arrays are like toy boxes where you can store multiple things in order!

Creating Your Toy Box

// Empty toy box


let emptyBox = [];

// Toy box with toys


let myToys = ["teddy bear", "robot", "ball", "puzzle"];

// Mixed toy box (you can store different types)


let mixedBox = ["toy car", 5, true, "doll"];

Playing with Your Toys

let fruits = ["apple", "banana", "orange"];

// Looking at specific toys (counting starts from 0!)


console.log(fruits[0]); // Prints: apple
console.log(fruits[1]); // Prints: banana

// Adding new toys


fruits.push("grape"); // Adds to the end
fruits.unshift("strawberry"); // Adds to the beginning

console.log(fruits); // ["strawberry", "apple", "banana", "orange", "grape"]


// How many toys do you have?
console.log(fruits.length); // Prints: 5

// Remove toys
fruits.pop(); // Removes last toy
fruits.shift(); // Removes first toy

Fun Array Methods - Like Special Tricks

let numbers = [1, 2, 3, 4, 5];

// Map - transform each item (like painting all toys red)


let doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]

// Filter - pick only certain items (like choosing only red toys)
let bigNumbers = numbers.filter(num => num > 3);
console.log(bigNumbers); // [4, 5]

// Find - look for one specific item


let foundNumber = numbers.find(num => num === 3);
console.log(foundNumber); // 3

// For each - do something with each toy


numbers.forEach(num => {
console.log("Number: " + num);
});

Real Example: Shopping List

let shoppingList = ["milk", "bread", "eggs"];

// Add items
shoppingList.push("butter", "cheese");

// Check if we need something


if (shoppingList.includes("milk")) {
console.log("Don't forget the milk!");
}

// Show the list


console.log("Shopping List:");
shoppingList.forEach((item, index) => {
console.log(`${index + 1}. ${item}`);
});
Objects - Your Treasure Chests
Objects are like special treasure chests where each treasure has a name tag!

Creating Your Treasure Chest

// Empty treasure chest


let emptyChest = {};

// Treasure chest with treasures


let myPet = {
name: "Buddy",
type: "dog",
age: 3,
isHappy: true
};

Looking at Your Treasures

let car = {
brand: "Toyota",
model: "Camry",
year: 2023,
color: "blue"
};

// Two ways to look at treasures


console.log(car.brand); // Prints: Toyota
console.log(car["model"]); // Prints: Camry

// Adding new treasures


car.owner = "John";
car["price"] = 25000;

console.log(car);

Objects with Functions (Methods)

let robot = {
name: "R2D2",
battery: 100,

// Functions inside objects are called methods


speak: function() {
console.log("Beep beep!");
},

// Modern way to write methods


walk() {
console.log(this.name + " is walking");
this.battery -= 10;
},

checkBattery: () => {
console.log("Battery: " + robot.battery + "%");
}
};

robot.speak(); // Prints: Beep beep!


robot.walk(); // Prints: R2D2 is walking
robot.checkBattery(); // Prints: Battery: 90%

Real Example: Student Report Card

let student = {
name: "Emma",
grade: 5,
subjects: {
math: 95,
science: 88,
english: 92
},

getAverageGrade() {
let scores = Object.values(this.subjects);
let total = scores.reduce((sum, score) => sum + score, 0);
return total / scores.length;
},

addSubject(subject, score) {
this.subjects[subject] = score;
}
};

console.log(`${student.name}'s average: ${student.getAverageGrade()}`);


student.addSubject("art", 98);
console.log(student.subjects);

Async/Await - Waiting Patiently


Sometimes we need to wait for things, like waiting for a pizza to be delivered!

Understanding Promises

// A promise is like ordering pizza - it will either arrive or something goes wrong
let pizzaOrder = new Promise((resolve, reject) => {
let pizzaReady = true; // Let's pretend pizza is ready

setTimeout(() => {
if (pizzaReady) {
resolve("🍕 Pizza is here!");
} else {
reject("😞 Pizza got burnt!");
}
}, 2000); // Wait 2 seconds
});

// Old way - using .then()


pizzaOrder
.then(message => console.log(message))
.catch(error => console.log(error));

The New Way: Async/Await

// Async function - a function that can wait for things


async function orderPizza() {
try {
console.log("Ordering pizza...");
let result = await pizzaOrder; // Wait here until pizza arrives
console.log(result);
console.log("Time to eat!");
} catch (error) {
console.log("Something went wrong: " + error);
}
}

orderPizza();

Real Example: Getting Data from Internet

// Pretend we're getting weather information


async function getWeather(city) {
try {
console.log(`Getting weather for ${city}...`);

// This simulates getting data from internet


let weatherData = await fetch(`https://api.weather.com/${city}`);
let weather = await weatherData.json();

console.log(`Weather in ${city}: ${weather.temperature}°F`);


return weather;
} catch (error) {
console.log("Couldn't get weather data: " + error);
}
}

// Using the function


getWeather("New York");
Simple Delay Function

// Helper function to wait


function wait(seconds) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}

async function countDown() {


console.log("Starting countdown...");

for (let i = 3; i > 0; i--) {


console.log(i);
await wait(1); // Wait 1 second
}

console.log("Blast off! 🚀");


}

countDown();

Modules - Sharing Your Toys


Modules are like sharing your toys with friends - you can give them some toys and use theirs
too!

Creating a Module (ES6 Modules)


mathHelpers.js - Your math toy box

// Functions you want to share


export function add(a, b) {
return a + b;
}

export function multiply(a, b) {


return a * b;
}

export const PI = 3.14159;

// Default export - the main toy you're sharing


export default function subtract(a, b) {
return a - b;
}

Using Modules
main.js - Using your friend's toys

// Import specific functions


import { add, multiply, PI } from './mathHelpers.js';
// Import the default export
import subtract from './mathHelpers.js';

// Import everything
import * as math from './mathHelpers.js';

// Using the imported functions


console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(PI); // 3.14159
console.log(subtract(10, 4)); // 6

// Using the everything import


console.log(math.add(2, 2)); // 4

HTML Setup for Modules


index.html

<!DOCTYPE html>
<html>
<head>
<title>Modules Example</title>
</head>
<body>
<h1>JavaScript Modules</h1>
<script type="module" src="main.js"></script>
</body>
</html>

Node.js Basics - JavaScript Outside the Browser


Node.js lets you use JavaScript outside of web browsers - like playing with your toys anywhere,
not just in your room!

Installing Node.js
Step 1: Download Node.js
1. Go to https://nodejs.org/
2. Download the LTS (Long Term Support) version
3. Install it like any other program
Step 2: Check if it worked
Open terminal/command prompt and type:

node --version
npm --version
Your First Node.js Program
hello.js

console.log("Hello from Node.js!");

// Node.js has special built-in modules


const os = require('os');
const path = require('path');

console.log("Your computer type:", os.type());


console.log("Current folder:", __dirname);
console.log("This file:", __filename);

Run it:

node hello.js

Working with Files


fileExample.js

const fs = require('fs');

// Writing to a file (like writing in a diary)


fs.writeFileSync('diary.txt', 'Today I learned JavaScript!');
console.log('Diary entry saved!');

// Reading from a file (like reading your diary)


const diaryContent = fs.readFileSync('diary.txt', 'utf8');
console.log('Diary says:', diaryContent);

// Async way (better for big files)


fs.writeFile('story.txt', 'Once upon a time...', (error) => {
if (error) {
console.log('Error writing story:', error);
} else {
console.log('Story saved!');
}
});

NPM - Your Toy Store


NPM is like a huge toy store where you can get tools made by other people!
Step 1: Create a package.json file

npm init -y

Step 2: Install a package (like buying a new toy)


npm install chalk

Step 3: Use the package


colorful.js

const chalk = require('chalk');

console.log(chalk.blue('Hello in blue!'));
console.log(chalk.red.bold('Hello in red and bold!'));
console.log(chalk.green.underline('Hello in green with underline!'));

Creating Your Own Module


calculator.js

function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a - b;
}

function multiply(a, b) {
return a * b;
}

// This is how you share functions in Node.js


module.exports = {
add,
subtract,
multiply
};

// Or export individually
// module.exports.add = add;

useCalculator.js

const calculator = require('./calculator');

console.log('5 + 3 =', calculator.add(5, 3));


console.log('10 - 4 =', calculator.subtract(10, 4));
console.log('6 × 7 =', calculator.multiply(6, 7));
Real Project: Simple To-Do List
todo.js

const fs = require('fs');

class TodoList {
constructor() {
this.todos = this.loadTodos();
}

addTodo(task) {
this.todos.push({
id: Date.now(),
task: task,
completed: false
});
this.saveTodos();
console.log(`Added: "${task}"`);
}

completeTodo(id) {
const todo = this.todos.find(t => t.id === id);
if (todo) {
todo.completed = true;
this.saveTodos();
console.log(`Completed: "${todo.task}"`);
}
}

listTodos() {
console.log('\n📝 Your To-Do List:');
this.todos.forEach(todo => {
const status = todo.completed ? '✅' : '⭕';
console.log(`${status} ${todo.task} (ID: ${todo.id})`);
});
}

loadTodos() {
try {
const data = fs.readFileSync('todos.json', 'utf8');
return JSON.parse(data);
} catch {
return [];
}
}

saveTodos() {
fs.writeFileSync('todos.json', JSON.stringify(this.todos, null, 2));
}
}

// Using the todo list


const myTodos = new TodoList();

myTodos.addTodo('Learn JavaScript');
myTodos.addTodo('Build a project');
myTodos.addTodo('Celebrate success');
myTodos.listTodos();

Resources for Further Learning

Official Documentation
JavaScript (MDN): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Node.js Official Docs: https://nodejs.org/en/docs/
NPM Documentation: https://docs.npmjs.com/

Helpful Websites
JavaScript.info: https://javascript.info/ - Excellent tutorials with interactive examples
FreeCodeCamp: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-struc
tures/ - Free interactive courses
Codecademy JavaScript Course: https://www.codecademy.com/learn/introduction-to-java
script

YouTube Video Tutorials


"JavaScript Tutorial for Beginners" by Programming with Mosh: https://www.youtube.co
m/watch?v=W6NZfCO5SIk - Comprehensive 1-hour crash course
"Node.js Tutorial for Beginners" by Programming with Mosh: https://www.youtube.com/
watch?v=TlB_eWDSMt4 - Great introduction to Node.js
"JavaScript ES6 Tutorial" by The Net Ninja: https://www.youtube.com/playlist?list=PL4cUx
eGkcC9gKfw25slm4CUDUcM_sXdml - Modern JavaScript features explained

Practice Platforms
Codepen.io: https://codepen.io/ - Write and test JavaScript in your browser
JSFiddle: https://jsfiddle.net/ - Another great online playground
Node.js REPL: Type node in your terminal for quick testing

Next Steps After This Guide


1. Build Projects: Create a weather app, calculator, or simple game
2. Learn a Framework: Try React, Vue, or Express.js
3. Practice Algorithm Problems: Use LeetCode or HackerRank
4. Join Communities: Reddit r/javascript, Stack Overflow, Discord servers
Remember: Learning JavaScript is like learning to ride a bike - it takes practice, but once you
get it, it becomes second nature! Start with small projects and gradually build bigger ones. Don't
worry if you don't understand everything at first - that's totally normal!
Happy coding! 🚀

You might also like