1

JavaScript for beginners

 2 years ago
source link: https://devm.io/javascript/javascript-features-beginners
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Special JavaScript features at a glance

JavaScript for beginners

04. Jul 2022


Nowadays, there is hardly a way to avoid JavaScript. So it makes sense for many programmers to at least deal with the basics. Those switching to a new language should first learn the basics and its special features.

Compared to other languages, JavaScript has some special features that are partly intentional, but partly due to the history of the language's development. Back when JavaScript was created, its wide distribution and many of its usage scenarios were unimaginable. This is also one of the reasons why the language core has changed significantly for the better in some places in recent years. This fact, along with the existence of tools like TypeScript that are based on JavaScript, makes the transition easier for developers who originally came from other programming languages. It doesn't matter which programming language you come from - you will always have to deal with the basic elements of JavaScript, since dialects like TypeScript are also built on the same foundation.

JavaScript’s type system

The statement that JavaScript has no type system is not quite correct. There are a number of primitive and complex data types. However, the handling of these seriously differs from other programming languages. The basic types in JavaScript are:

  • Boolean
  • Number
  • String
  • Null, undefined
  • Symbol

These base types are passed by Value. So if you pass a string to a function, it will be copied. If you modify the value inside the function, the value outside does not change. Listing 1 illustrates this relationship.

Listing 1: By-Value passing of values

let name = 'Klaus';
 
function doSomethingWithName(name) {
  name = 'Petra';
  console.log(name); // Petra
}
 
doSomethingWithName(name);
console.log(name); // Klaus

Regardless of the effect of this example, it is bad style to manipulate the arguments of a function directly and rely on any side effects. A better idea is to make a deep copy of the argument, continue working with it, and return the modified value. This becomes especially interesting when dealing with complex data types such as arrays or objects passed by reference. This means that you pass only the reference to the object to a function. Changing the object affects the original object and creates a possibly unintended side effect. You can see how this plays out in the code in Listing 2.

Listing 2: By-Value passing of objects

let person = { name: 'Klaus' };
 
function doSomethingWithPerson(person) {
  person.name = 'Petra';
  console.log(person.name); // Petra
}
 
doSomethingWithPerson(person);
console.log(person.name); // Petra

You can create a deep copy of an object in several ways. In most cases, however, you should use an established library. Here you have the choice between simple and lightweight solutions like Lodash and Immutability Helper or extensive libraries like Immer and immutable. js. You should choose the appropriate library depending on your use case.

Otherwise, JavaScript objects are key-value stores whose keys must always be strings and whose values can be of any data type. This allows you to create simple properties with primitive values, as well as child objects. If a property contains a function object, this can be used as a method of the object. Since ECMAScript 6, there is a shorthand notation that lets you omit the function keyword from such methods. Listing 3 contains an example of this.

Listing 3: Method shortcut
const klaus = {
  firstname: 'Klaus',
  lastname: 'Müller',
  getFullName() {
    return `${this.firstname} ${this.lastname}`;
  },
};

Arrays are the most powerful data structures included in the JavaScript core. They are objects that have a sequential numeric index as the key for the properties. You can choose the values as you wish. In addition to these basic properties, arrays have a number of methods that you can use to work with the array. For example, it is possible to iterate over the array, transform the elements with the map method, or find out whether a certain condition applies to at least one element with the some method.

JavaScript's loose type system provides a great deal of flexibility that many developers don't want to be taken away from. However, this also creates a number of problems. For example, you can assign a string as a value to a variable and then pass it a number at a later point in time. These dynamic changes of the type of a variable in JavaScript do not represent an error, but reliability is limited at this point, especially in large applications. TypeScript offers a solution to this problem. This language adds type information and other features such as interfaces, generics, or enums to the JavaScript language scope. The TypeScript compiler performs a static check of the source code, as shown below, and translates the TypeScript code into JavaScript, which you can execute in the browser or server-side in Node.js:

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

Scoping

Another important aspect of a programming language is the scope of variables. JavaScript has four scopes:

  • Global Scope: The global scope is the widest in JavaScript. It covers the entire application. Variables declared in the global scope pose a danger to the application in that they cannot be released by the JavaScript engine's garbage collector during the application's runtime because there is always a reference to the respective memory area. For this reason, and to avoid any naming conflicts, you should use global variables as sparingly as possible.
  • Function Scope: In the original version of JavaScript, the function scope was the smallest unit in which you could declare a variable. The function scope includes a function and all its subfunctions.
  • Closure Scope: The Closure Scope is an extension of the function scope by the creating context of the function. This means that you not only have access to the function itself, but also to the surrounding scope. So if a function is defined within a function and returned from it, it still has access to the scope of the defining function, even if the processing of this function has already ended. This mechanism can be used to define variables that can only be accessed through such a function. Listing 4 contains an example of this.
  • Block Scope: The block scope is the youngest representative of the JavaScript scopes. A block in JavaScript is usually enclosed by curly braces. For example, a function represents a block, but an if condition, a for loop, or a try-catch statement are also blocks. With the block scope, you have much finer and therefore better control over the variables in your application.
Listing 4: Private variables in JavaScript
function myPrivate() {
  let value = ''; // "private" variable
  return {
    setValue(v) { // write access
      value = v;
    },
    getValue() { // read access
      return value;
    },
  };
}
const myPriv = myPrivate();
 
console.log(value); // ReferenceError
myPriv.setValue('Klaus');
console.log(myPriv.getValue()); // Klaus

To declare variables, use the let keyword. It was introduced with the 6th version of the language standard and declares variables on the block level. The older var keyword is hardly used anymore in modern applications. With block variables, you can cover all the cases that you also implemented with function variables, with the bonus that you have even more control over the validity of the variables. Variables in JavaScript are complemented by the const keyword. This allows you to define constant values. For primitive data types, this means that the value of the variable cannot be changed. When you use const in conjunction with a composite type such as an object, only the reference to the object is constant. You can change the object itself and, for example, assign new property values to it. As a rule for handling variables, it has become established in many JavaScript applications to basically work with const. Only if the value of a variable is really overwritten, let is used.

JavaScript prototype-oriented object orientation

The object orientation of JavaScript is very different from most other programming languages, such as Java. JavaScript relies on prototype-based object orientation. The basis is a constructor function. This can be any function. For the creation of an instance of such a constructor, the new operator is used. Within the constructor, the instance is referenced via this, so that properties...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK