JavaScript Tutorial - Learn JavaScript Basics

Learn JavaScript basics with this comprehensive tutorial. Covers strings, variables, arrays, if statements, and file reading. Free and easy to follow!

JavaScript Tutorial

Getting Started with JavaScript

This tutorial provides a basic introduction to JavaScript. We'll cover fundamental concepts such as strings, variables, arrays, conditional statements, and file input/output.

Strings and Variables

Let's begin by declaring variables and working with strings:

var test = 'ok';
console.log(test); // Output: ok

var test = 'ok2'; // Overwriting with var
console.log(test); // Output: ok2

const constantTest = 'ok';
//const constantTest = 'ok2'; // Uncaught SyntaxError: Identifier 'constantTest' has already been declared

const name = 'ruan';
var msg = `my name is ${name}`;
console.log(msg); // Output: my name is ruan

var msg = `my name is:
- ${name}`;
console.log(msg); // Output: my name is:
// - ruan

Arrays

Arrays are used to store collections of data:

var dict = [];
dict.push({
    key:   "name",
    value: "ruan"
});
console.log(dict); // Output: [{ key: 'name', value: 'ruan' }]

Conditional Statements (If Statements)

Conditional statements allow you to control the flow of your program based on certain conditions:

var x = 2;
if (x == 0) {
  console.log('x is 0');
} else if (x > 1) {
  console.log('x is more than 1');
} else {
  console.log('x is probably 1');
} // Output: x is more than 1


var event = {'name': 'ruan', 'surname': 'bekker', 'age': 34, 'severity': 'Low', 'skip': false};
if ((!event.skip && event.name == 'ruan')) {
  console.log('true'); // Output: true
}

if ((!event.skip && event.name == 'frank') || (!event.skip && event.age == 34)) {
  console.log('true'); // Output: true
}

if (!event.skip && (event.name == 'frank' || event.age == 34)) {
  console.log('true'); // Output: true
}

Reading File Contents

Here's how to read the contents of a file using Node.js's fs module:

const fs = require('fs');
const fileName = "/tmp/foo-bar";
const myText = fs.readFileSync(fileName, "utf-8");
console.log(myText); // Output: hello (assuming the file contains "hello")

Further Exploration

This tutorial has only scratched the surface of JavaScript's capabilities. To delve deeper, explore resources like the Mozilla Developer Network (MDN) and various online courses.

Remember to consult the official documentation for more detailed information and advanced techniques.