JavaScript Basic Syntax
This is a super-quick introduction to the basic syntax of the language, enabling students to use it when solving daily exercises, while a deeper dive into the language awaits in later lessons.
Variables
// Using var (old way)
var name = "John";
// Using let (block-scoped)
let age = 30;
// Using const (constant value)
const isStudent = true;
copy
Data Types
Note: Some of the types are not included.
// String
let name = "John";
// Number
let age = 25;
// Boolean
let isStudent = true;
// Undefined
let undefinedValue;
// Null
let emptyValue = null;
// Object
let person = {
firstName: "Jane",
lastName: "Doe"
};
// Array
let colors = ["red", "green", "blue"];
copy
Operators
// Arithmetic Operators
let sum = 10 + 5; // Addition
let difference = 10 - 5; // Subtraction
let product = 10 * 5; // Multiplication
let quotient = 10 / 5; // Division
let remainder = 10 % 3; // Modulus
// Assignment Operators
let x = 10;
x += 5; // x = x + 5;
// Comparison Operators
let isEqual = (10 == "10"); // true (loose equality)
let isStrictEqual = (10 === 10); // true (strict equality)
let isNotEqual = (10 != 5); // true
let isGreater = (10 > 5); // true
// Logical Operators
let and = true && false; // false
let or = true || false; // true
let not = !true; // false
copy
Conditionals
let age = 18;
if (age < 18) {
console.log("You are a minor.");
} else if (age >= 18 && age < 65) {
console.log("You are an adult.");
} else {
console.log("You are a senior citizen.");
}
// Ternary Operator
let canVote = (age >= 18) ? "Yes" : "No";
copy
Loops
// For Loop
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}
// While Loop
let i = 0;
while (i < 5) {
console.log("While Iteration:", i);
i++;
}
// Do-While Loop
let j = 0;
do {
console.log("Do-While Iteration:", j);
j++;
} while (j < 5);
copy
Functions
// Function Declaration
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("John"));
// Function Expression
const add = function(x, y) {
return x + y;
};
console.log(add(5, 10));
// Arrow Function (ES6)
const multiply = (x, y) => x * y;
console.log(multiply(3, 4));
copy
Objects
let car = {
make: "Toyota",
model: "Corolla",
year: 2020,
start: function() {
console.log("Car started.");
}
};
console.log(car.make); // Accessing property
car.start(); // Calling method
copy
Arrays
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Accessing array elements
fruits.push("orange"); // Adding an element to the array
fruits.pop(); // Removing the last element from the array
console.log(fruits.length); // Getting the length of the array
copy
String Methods
let text = "Hello, World!";
console.log(text.length); // Length of the string
console.log(text.toUpperCase()); // Convert to uppercase
console.log(text.toLowerCase()); // Convert to lowercase
console.log(text.indexOf("World")); // Find the position of a substring
console.log(text.slice(0, 5)); // Extract a part of the string
copy
Array Methods
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8, 10]
let evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4]
let sum = numbers.reduce(function(total, num) {
return total + num;
}, 0);
console.log(sum); // 15
copy
Events
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});
copy
Error Handling
try {
let result = someFunction();
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("This will always run.");
}
copy
JSON (JavaScript Object Notation)
let jsonString = '{"name": "John", "age": 30, "city": "New York"}';
let jsonObject = JSON.parse(jsonString); // Convert JSON string to JavaScript object
console.log(jsonObject.name); // Accessing the object property
let newJsonString = JSON.stringify(jsonObject); // Convert JavaScript object to JSON string
console.log(newJsonString);
copy
Simple Problem Examples
1. Sum of Two Numbers
Problem: Write a function that takes two numbers and returns their sum.
function sum(a, b) {
return a + b;
}
console.log(sum(3, 4)); // Output: 7
copy
2. Check if a Number is Even or Odd
Problem: Write a function that checks if a number is even or odd.
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
copy
3. Find the Largest Number in an Array
Problem: Write a function that returns the largest number in an array.
function findLargest(arr) {
return Math.max(...arr);
}
console.log(findLargest([1, 5, 3, 9, 2])); // Output: 9
copy
4. Reverse a String
Problem: Write a function that reverses a given string.
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // Output: "olleh"
copy
5. Factorial of a Number
Problem: Write a function that calculates the factorial of a number.
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
copy
6. Check if a String is a Palindrome
Problem: Write a function that checks if a string is a palindrome.
function isPalindrome(str) {
let reversed = str.split('').reverse().join('');
return str === reversed;
}
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("hello")); // Output: false
copy
7. FizzBuzz
Problem: Write a function that prints numbers from 1 to 100. For multiples of 3, print “Fizz” instead of the number, and for multiples of 5, print “Buzz”. For numbers that are multiples of both 3 and 5, print “FizzBuzz”.
function fizzBuzz() {
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
}
fizzBuzz();
copy
8. Find the Sum of an Array
Problem: Write a function that returns the sum of all numbers in an array.
function sumArray(arr) {
return arr.reduce((total, num) => total + num, 0);
}
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
copy
9. Count Vowels in a String
Problem: Write a function that counts the number of vowels in a given string.
function countVowels(str) {
let count = 0;
const vowels = "aeiouAEIOU";
for (let char of str) {
if (vowels.includes(char)) {
count++;
}
}
return count;
}
console.log(countVowels("hello")); // Output: 2
console.log(countVowels("javascript")); // Output: 3
copy
10. Generate a Random Number
Problem: Write a function that generates a random number between two given numbers.
function randomInRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInRange(1, 10)); // Output: a random number between 1 and 10
copy
These problems are great for practicing basic JavaScript concepts like functions, loops, conditionals, and array manipulation.
Concepts
Front-End Web Development Concepts
HTML (Hypertext Markup Language): The standard language for creating web pages, defining the structure of content.
CSS (Cascading Style Sheets): Used to style and layout web pages, including colors, fonts, and spacing.
JavaScript: A programming language used to add interactivity to web pages, such as animations and form validation.
Responsive Design: An approach to web design that ensures websites work well on a variety of devices and screen sizes.
DOM (Document Object Model): A programming interface that allows scripts to update the content, structure, and style of a document dynamically.
AJAX (Asynchronous JavaScript and XML): A technique for creating faster and more dynamic web pages by updating parts of a web page without reloading the whole page.
Single Page Application (SPA): A web application that interacts with the user by dynamically rewriting the current page, rather than loading entire new pages from the server.
Progressive Web Apps (PWA): Web applications that use modern web capabilities to deliver an app-like experience to users.
Bootstrap: A popular front-end framework for developing responsive and mobile-first websites.
SASS/LESS: CSS preprocessors that allow you to use variables, nested rules, and functions in your CSS.
Client-Side Rendering (CSR): Rendering web content in the browser using JavaScript, often used in single-page applications.
Cross-Browser Compatibility: Ensuring that a website works consistently across different web browsers.
Web Accessibility: The practice of making websites usable by people of all abilities and disabilities.
UX/UI Design (User Experience/User Interface): The process of enhancing user satisfaction by improving the usability, accessibility, and aesthetics of a website.
Back-End Web Development Concepts
Server: A system that provides data, services, or resources to other computers, known as clients, over a network.
Database: Organized collection of data that is stored and accessed electronically, often used in the back-end of websites.
SQL (Structured Query Language): A language used to manage and manipulate databases.
NoSQL: A type of database that provides a mechanism for storage and retrieval of data modeled in means other than tabular relations (used in SQL databases).
API (Application Programming Interface): A set of rules and tools that allows different software applications to communicate with each other.
RESTful Services: Web services that adhere to the REST (Representational State Transfer) architecture, using HTTP requests to access and use data.
GraphQL: A query language for your API, providing a more efficient, powerful, and flexible alternative to REST.
MVC (Model-View-Controller): A design pattern used in software engineering to separate the application logic, user interface, and control flow.
Authentication: The process of verifying the identity of a user or process.
Authorization: The process of granting or denying a user’s access to resources.
JWT (JSON Web Token): A compact, URL-safe means of representing claims to be transferred between two parties, often used for authorization.
OAuth: An open standard for access delegation commonly used for token-based authentication.
Session Management: Managing user sessions on the server, including how long they last and how they are terminated.
Cookies: Small pieces of data stored on the user’s browser that help websites remember information about the user.
Session Storage/Local Storage: Web storage mechanisms that allow websites to store data locally within the user’s browser.
Caching: The process of storing data temporarily to speed up future access.
Load Balancing: Distributing network or application traffic across multiple servers to ensure reliability and performance.
Database Indexing: A data structure that improves the speed of data retrieval operations on a database table.
ORM (Object-Relational Mapping): A technique for converting data between incompatible type systems using object-oriented programming languages.
SQL Injection: A code injection technique that might destroy your database, one of the most common web hacking techniques.
Web Security: Practices and tools used to protect web applications from threats like hacking, data breaches, and viruses.
SSL/TLS (Secure Sockets Layer/Transport Layer Security): Protocols that encrypt data transferred over the internet, securing communication between web browsers and servers.
WebSocket: A protocol that enables real-time, two-way communication between a client and server.
Microservices: An architectural style that structures an application as a collection of loosely coupled services.
Containerization (Docker): A lightweight form of virtualization that packages an application and its dependencies into a container.
Continuous Integration/Continuous Deployment (CI/CD): Practices that involve automatically testing and deploying code changes to ensure faster, more reliable software delivery.
Reverse Proxy: A server that sits in front of web servers and forwards client requests to those servers.
Content Delivery Network (CDN): A network of servers that delivers web content to users based on their geographic location, improving load times.
Web Server: Software that serves web pages to users by processing incoming requests and delivering content.
Application Server: A server that provides business logic and manages application operations between users and back-end databases.
Middleware: Software that connects different components of an application, allowing them to communicate and manage data.
Logs/Monitoring: The process of recording, analyzing, and responding to the operational data generated by applications and servers.
Queues (e.g., RabbitMQ, Kafka): A system that manages tasks or messages between distributed services or applications.
Web Frameworks: Tools and libraries designed to help streamline the development process (e.g., Django for Python, Laravel for PHP).
Database Migration: The process of transferring data between storage types, formats, or systems.
Cloud Computing: The delivery of computing services (servers, storage, databases, networking, software) over the cloud.
Load Testing: The process of putting demand on a system and measuring its response to ensure it can handle expected loads.
Scalability: The ability of a system to handle increased load by adding resources.
Server-Side Rendering (SSR): A technique for rendering web pages on the server rather than in the browser, improving load times and SEO.
Environment Variables: Variables that are defined outside of the application code and are used to configure the environment in which the application runs.
Version Control (e.g., Git): A system that records changes to files over time, allowing developers to track history and collaborate on projects.
General Technical Vocabulary
- Access
- Account
- Action
- Activate
- Add
- Admin
- Advanced
- Algorithm
- Analyze
- API (Application Programming Interface)
- Application
- Array
- Assign
- Asynchronous
- Attribute
- Authentication
- Authorization
- Backup
- Binary
- Boolean
- Breakpoint
- Browser
- Buffer
- Bug
- Build
- Cache
- Callback
- Certificate
- Character
- Class
- Client
- Code
- Compile
- Component
- Configuration
- Connect
- Console
- Constant
- Constructor
- Container
- Context
- Control
- Convert
- Cookie
- Credentials
- Cryptography
- CSS (Cascading Style Sheets)
- Data
- Database
- Debug
- Default
- Deploy
- Dependency
- Design
- Desktop
- Device
- Development
- Directory
- Document
- Domain
- Download
- Element
- Encode
- Encryption
- Endpoint
- Environment
- Error
- Execute
- Export
- Extension
- Feature
- File
- Firewall
- Flag
- Font
- Framework
- Function
- Gateway
- Git
- Header
- Host
- HTML (Hypertext Markup Language)
- HTTP/HTTPS (Hypertext Transfer Protocol/Secure)
- Identifier
- Import
- Index
- Input
- Instance
- Interface
- Internet
- IP Address
- JavaScript
- Kernel
- Key
- Language
- Library
- Link
- Load
- Log
- Loop
- Machine
- Memory
- Method
- Mobile
- Module
- Network
- Node
- Notification
- Object
- Open Source
- Operator
- Option
- Output
- Package
- Parameter
- Parse
- Password
- Path
- Permission
- Pixel
- Platform
- Plugin
- Port
- Process
- Program
- Protocol
- Proxy
- Query
- Queue
- Record
- Redirect
- Refactor
- Register
- Repository
- Request
- Resource
- Response
- Restore
- Return
- Route
- Runtime
- Script
- Search
- Security
- Select
- Server
- Service
- Session
- Setting
- Shell
- Signal
- Socket
- Source
- Stack
- Storage
- String
- Structure
- Submit
- Syntax
- System
- Tag
- Template
- Terminal
- Thread
- Token
- Tool
- Traffic
- Transaction
- Transfer
- Trigger
- Type
- UI/UX (User Interface/User Experience)
- Update
- Upload
- User
- Validate
- Value
- Variable
- Version
- Virtual
- Visual
- Web
- Website
- Widget
- Window
- Wireframe
- Workflow
- Programming-Specific Vocabulary
- Abstract
- Argument
- Array
- Assign
- Boolean
- Class
- Closure
- Command
- Compile
- Conditional
- Constructor
- Data Type
- Debug
- Declaration
- Definition
- Delegate
- Dependency
- Enumeration
- Event
- Exception
- Expression
- Framework
- Function
- Inheritance
- Instance
- Interface
- Iteration
- Lambda
- Library
- Literal
- Loop
- Method
- Namespace
- Object
- Operator
- Overload
- Parameter
- Polymorphism
- Procedure
- Property
- Protocol
- Recursion
- Return
- Scope
- Sequence
- Statement
- Syntax
- Thread
- Tuple
- Type
- Variable
- Web Development Vocabulary
- AJAX (Asynchronous JavaScript and XML)
- Anchor
- Attribute
- Backend
- Base URL
- Block Element
- Bootstrap
- Browser Compatibility
- Cache-Control
- Cascading
- CDN (Content Delivery Network)
- Charset
- Class Selector
- Client-Side
- CMS (Content Management System)
- Cross-Origin
- CSS Grid
- DOM (Document Object Model)
- DOCTYPE
- Element Selector
- Emmet
- Favicon
- Flexbox
- Font-Family
- Frontend
- Grid System
- Header Tag
- ID Selector
- Inline Element
- JQuery
- Media Query
- Meta Tag
- Modal
- Navigation Bar
- Padding
- Positioning
- Pseudo-Class
- Responsive Design
- Selector
- Server-Side
- Session Storage
- SPA (Single Page Application)
- Styling
- Tag
- UI Components
- Viewport
- WebSocket
- Wrapper
- Cloud and DevOps Vocabulary
- API Gateway
- CI/CD (Continuous Integration/Continuous Deployment)
- Cloud Computing
- Cluster
- Containerization
- Deployment
- DevOps
- DNS (Domain Name System)
- Environment Variable
- Infrastructure
- Instance
- Kubernetes
- Load Balancer
- Microservices
- Provisioning
- Scalability
- Service Mesh
- Serverless
- Terraform
- Virtual Machine (VM)
- Security Vocabulary
- Authentication
- Authorization
- Backdoor
- Brute Force
- CORS (Cross-Origin Resource Sharing)
- CSRF (Cross-Site Request Forgery)
- Encryption
- Firewall
- Hashing
- HTTPS
- Injection
- Malware
- Phishing
- RSA (Rivest-Shamir-Adleman)
- SSL/TLS
- Token
- Vulnerability
- Zero-Day
Phrases
- Access: “You need to request access to the database before you can retrieve any data.”
- Account: “Create an account to access the premium features of the application.”
- Activate: “Activate your account by clicking on the link sent to your email.”
- Add: “Add the new user to the system by filling out the registration form.”
- Admin: “The admin panel allows you to manage users and settings.”
- Advanced: “This advanced course covers complex algorithms and data structures.”
- Algorithm: “The algorithm sorts the data in ascending order.”
- Analyze: “Analyze the log files to identify any errors in the system.”
- API (Application Programming Interface): “The API allows developers to interact with the service programmatically.”
- Application: “This web application is built using React and Node.js.”
- Array: “Store the list of items in an array for easy access and manipulation.”
- Assign: “Assign a value to the variable before using it in the function.”
- Asynchronous: “Asynchronous operations allow the program to continue running while waiting for a task to complete.”
- Attribute: “The src attribute in the img tag specifies the path to the image.”
- Authentication: “Authentication is required to access secure areas of the website.”
- Authorization: “Authorization determines what resources a user can access after authentication.”
- Backup: “Make sure to backup your data regularly to prevent loss.”
- Binary: “Data is stored in binary format on the disk.”
- Boolean: “A boolean value can be either true or false.”
- Breakpoint: “Set a breakpoint in the code to pause execution and inspect variables.”
- Browser: “The website is optimized for all major browsers.”
- Buffer: “The buffer temporarily holds data before it’s processed.”
- Bug: “There’s a bug in the code that causes the application to crash.”
- Build: “Build the project before deploying it to the server.”
- Cache: “Clearing the cache can help resolve loading issues in your browser.”
- Callback: “Use a callback function to execute code after an asynchronous operation completes.”
- Certificate: “The SSL certificate ensures secure communication between the client and server.”
- Character: “The string contains 20 characters, including spaces.”
- Class: “Define a class in the code to represent objects with common properties.”
- Client: “The client sends a request to the server to retrieve data.”
- Code: “Write clean and efficient code to improve the application’s performance.”
- Compile: “Compile the code to check for syntax errors before running it.”
- Component: “Each component in a React application manages its own state.”
- Configuration: “Update the configuration file to change the database connection settings.”
- Connect: “Connect to the database using the provided credentials.”
- Console: “The console displays error messages and logs during development.”
- Constant: “Declare a constant for values that should not change.”
- Constructor: “The constructor function initializes the object’s properties.”
- Container: “Containers allow you to run applications in isolated environments.”
- Context: “The context provides information about the current state of the application.”
- Control: “Use control statements like if and switch to manage the flow of the program.”
- Convert: “Convert the data type from string to integer before performing calculations.”
- Cookie: “Cookies store user preferences and session information.”
- Credentials: “Enter your credentials to log in to the system.”
- Cryptography: “Cryptography is used to secure data by encrypting it.”
- CSS (Cascading Style Sheets): “Use CSS to style the appearance of your website.”
- Data: “The data is stored in a relational database for easy access.”
- Database: “The database holds all the user information and transaction records.”
- Debug: “Debug the code to find and fix errors.”
- Default: “The default value is used if no input is provided by the user.”
- Deploy: “Deploy the application to the production server after testing.”
- Dependency: “The project has several dependencies that need to be installed.”
- Design: “The design phase involves creating wireframes and mockups.”
- Desktop: “This application is available for both desktop and mobile platforms.”
- Device: “Ensure the website is responsive on all devices.”
- Development: “The development environment is where you write and test your code.”
- Directory: “Navigate to the project directory to access the source files.”
- Document: “The HTML document is structured with various tags and elements.”
- Domain: “Register a domain name for your website.”
- Download: “Download the latest version of the software from the official website.”
- Element: “Each HTML element represents a different part of the web page.”
- Email: “Use a valid email address to sign up for the newsletter.”
- Encode: “Encode the data before sending it over the network.”
- Encryption: “Encryption ensures that data is secure during transmission.”
- Endpoint: “The API endpoint is where the client sends requests to the server.”
- Environment: “Set up the development environment before starting the project.”
- Error: “An error occurred while processing your request.”
- Execute: “Execute the script to run the program.”
- Export: “Export the data to a CSV file for analysis.”
- Extension: “Install a browser extension to enhance functionality.”
- Feature: “This new feature allows users to share content directly from the app.”
- File: “Save the file with a .txt extension.”
- Firewall: “The firewall protects the network from unauthorized access.”
- Flag: “Use a flag to indicate whether the operation was successful.”
- Font: “Choose a readable font for the website’s text.”
- Framework: “React is a popular JavaScript framework for building user interfaces.”
- Function: “Call the function to perform a specific task in the program.”
- Gateway: “The gateway manages the flow of data between networks.”
- Git: “Use Git to track changes in your code repository.”
- Header: “The HTTP header contains metadata about the request.”
- Host: “The website is hosted on a cloud server.”
- HTML (Hypertext Markup Language): “HTML is the standard language for creating web pages.”
- HTTP/HTTPS (Hypertext Transfer Protocol/Secure): “HTTPS secures the communication between the client and server.”
- Identifier: “Use a unique identifier for each element in the HTML document.”
- Import: “Import the module to use its functions in your code.”
- Index: “The index file is the entry point for the application.”
- Input: “The user input is validated before processing.”
- Instance: “Create an instance of the class to use its methods.”
- Interface: “The user interface should be intuitive and easy to navigate.”
- Internet: “The application requires an internet connection to function properly.”
- IP Address: “The IP address identifies the device on the network.”
- JavaScript: “JavaScript is used to add interactivity to web pages.”
- Kernel: “The kernel is the core component of an operating system.”
- Key: “The key is used to encrypt and decrypt the data.”
- Language: “Python is a popular programming language for data analysis.”
- Library: “Use a JavaScript library like jQuery to simplify DOM manipulation.”
- Link: “Click the link to view more details.”
- Load: “The page takes a few seconds to load all the resources.”
- Log: “Check the log files for any errors during the operation.”
- Loop: “The loop iterates over the array to process each element.”
- Machine: “The virtual machine runs multiple operating systems simultaneously.”
- Memory: “The application consumes a lot of memory during execution.”
- Method: “Call the method to perform an action on the object.”
- Mobile: “The mobile version of the website is optimized for touchscreens.”
- Module: “The module contains reusable functions for the application.”
- Network: “The network connection is required to access the server.”
- Node: “Each node in the DOM tree represents an element in the HTML document.”
- Notification: “The user receives a notification when the download is complete.”
- Object: “Create an object to store data and methods.”
- Open Source: “The software is open source, meaning the source code is freely available.”
- Operator: “Use the + operator to add two numbers.”
- Option: “Select an option from the dropdown menu.”
- Output: “The output of the program is displayed in the console.”
- Package: “Install the package using the package manager.”
- Parameter: “Pass parameters to the function to customize its behavior.”
- Parse: “Parse the JSON data to extract the values.”
- Password: “Enter your password to log in to the