DEV Community

Cover image for Core Concepts of Programming through JavaScript
Prerana Nawar
Prerana Nawar

Posted on • Updated on

Core Concepts of Programming through JavaScript

In this article, we will try to understand some of the core concepts of Programming through Javascript. If you want to learn JavaScript to pursue a career in development, then you are in the right place.

JavaScript is simple and easy to learn programming language. Now-a-days, it has become an inseparable part of any core technologies of the internet.

So, let's dive into to understand the programming fundamentals and basic-object oriented concepts using javascript syntax. The concepts covered here lay the foundation for javascript as well as the concepts in this article are generic to all programming langauges.

Alt Text

Content:

  1. What is a Program ?
  2. Variables, Statements and Expressions
  3. Conditional Statements
  4. Functions
  5. Loops
  6. Arrays
  7. Objects

What’s a Program?

  • As we all know, Computer is a machine whose role is to execute quickly a series of tasks given to it.
  • A Program is nothing but a list of actions given to a computer.
  • The Programmer’s task is to create programs.
  • A Programming language is a way to give orders to a computer. It’s a bit like a human language! Each programming language has its own vocabulary ( keywords that each play a specific role) and grammar (rules defining how to write programs in that language).

Alt Text

Variables:

  • At the end of the day, a program's goal is to do something with the data, or in other words, to process the data. Variable as a container used to store a piece of data (value) that your program may need for processing.
  • variable is composed of two elements : name and value. The type of a variable depends of its value.
  • Think of a variable as a box that contains a value. This box is stored in warehouse. The location of every box is recorded, just like your computer records the location of your variable in memory. Alt Text
  • A value is a piece of data you put in a variable. To know what each box is for, you need to label them. In programming we say: assigning a name to a variable. Values of variables can be modified.
  • Remember: The name of a variable should always reflect the meaning of its contents, like when you label boxes.

Alt Text

  • Some of the general suggestions while naming your variable:
    • Use descriptive names
    • Follow the common naming convention of the lanague you are using
      • If a variable is multi-word, you can use:
        • Camel-case: let inputNumber = 0;
        • Pascal Case: let InputNumber = 0;
        • Snake case: let input_number = 0;

Expressions and Statements:

  • Statements and Expressions are two most important terms in any programming language. But often people don't know what's the main difference is.
  • So, Expression is a code that produces a value. An expression is created by combining variables, values and operators. That's why we always say Arthimetic Expressions and Logical Expressions because it always outputs a value whether it be numerical value or boolean value. If you don't know what's artimetic & logical operator take a look at this docs.
    • 10 + 20; // Expression that produces the numeric value 30
    • 10 > 9; // produces to boolean value true
  • On the other hand, a statement is an instruction to perform a specific action, and that's why we say conditional statements because conditional statements execute statements based on the value of an expression.

Example : let number = 10;

Example of Conditional Statement:

     if (expression) 
        statement 1
     else 
        statement 2
Enter fullscreen mode Exit fullscreen mode

Conditional Statements

Alt Text

  • By using Conditional statements we can control the flow of our program. They allow us to execute code only under certain conditions that we define and the block of code will only execute if the condition in parenthesis is met.

    Conditional statements rely on providing a Boolean value that can determine whether a code block (the statements between the {} curly braces) should execute.

    if statements:

    • The most common flow-control statement in almost every programming language is the if statement.
    • Suppose we ask a user to enter a number and then check whether the number is positive.

       Enter a Number
       If the Number is positive
            Display a message
      

      The message will be displayed only if the condition i.e only if the Number is positive.

    • Think of it as : “If the condition is true, then executes the instructions contained in the code block”.

    • Syntax:

       if ( expression ) {
            // *block of code to be executed if the condition is true
       } 
      

    When the code block has only one statement, braces may be omitted. As a beginner, you should always use braces when writing your conditions.

    if/else statements

    • Now we will check if the number is positive or negative

       Enter a Number
       if the Number is positive
           Display a message "Your Number is a Positive Number"
       else
           Display a message "Your Number is a Negative Number"
      
    • You can translate an if/else statement like this: “If the condition is true, then execute this first set of code; otherwise, execute this next set of code”.

    • Only one of the two code blocks will be executed. The condition in the else if statement will only be evaluated after the first if condition is false.

    • Syntax:

       if ( expression ) {
          // *block of code to be executed if the condition is true*
       } else {
          // *block of code to be executed if the condition is false
       }
      

    if/else if/else statements - Nesting conditions

    • But what is the User Enter's a zero in that case we can use a Nesting condition

       Enter a Number
       if the Number is positive (Number > 0)
          Display a message "Your Number is a Positive Number"
       else if Number is negative (Number < 0)
          Display a message "Your Number is a Negative Number"
       else
          Display a message "Your Entered Zero"
      
    • Multiple else if statements can be chained together like above.

    • The condition in the else if statement will only be evaluated after the first if condition is false. If the else if condition is also false, the code in the else block will execute.

    • Syntax:

       if ( expression1 ) {
          // *block of code to be executed if expression1 is true*
       } else if ( expression2 ) {
          // *block of code to be executed if the condition1 is false and expression2 is true
       } else {
          // *block of code to be executed if the condition1 is false and condition2 is false
       }
      

Functions:

Alt Text

  • Functions are a crucial concept in pretty much any programming language. A function is a group of statements that performs a particular task. Functions allow us to repeat tasks that involve a similar sequence of steps (processing).
  • Syntax for Declaring and Calling / Invoking a Function

      function myFunctionName( parameter1, parameter2 ) { // declaring the function
            // *code to be executed
     }
     myFunctionName(argument1, argument2); // calling the function
    
  • The parentheses themselves are always required for every function you defined and they allow you to receive arguments that would be input to your function.Then we have curly braces,curly braces surround the function body and that is the code which executes when this function gets called.

1. Functions with no parameters and no return types:

  • Syntax for Declaring and Calling / Invoking a Function

     function myFunctionName() {
            console.log("");
     }
     myFunctionName();
    
  • Example:

     function welcomeMessage() {
            console.log("Hello Javascript");
     }
    welcomeMessage();
    
  • Remember: In this function we are not taking any input as well as we are not returning any output we are just logging / printing the output.

2. Functions with parameters and no return types:

  • Functions accept outside values. We can do that by defining a function with parameters. Parameters are the input to the function. Parameters are variables listed in the function declaration that are specified inside () by the name.
  • Each value is assigned to a parameter in the order they are defined. Parameters are the variables declared in a function and the values that are passed to that function are called arguments.
  • Syntax:

     function myFunctionName( parameter1, parameter2 ) { 
            // *code to be executed
     }
    myFunctionName(argument1, argument2);
    
  • Example:

     function sumOfNumbers(num1, num2) {
            let sum = num1 + num2; 
            console.log(sum);
     }
     sumOfNumbers(10,20);
    

3. Functions with return Type and no parameters:

  • If you expect the function to give back some value in return , it should include a return statement (which is done by using the keyword return ), followed by the value you want to be returned.
  • If you don’t expect your function to return a value, you do not have to include a return statement. This return value can be of any type (number, string, etc).
  • Remember: Any statements after return Satement won't be executed.
  • Syntax:

     function myFunctionName( parameter1, parameter2 ) { 
            // *code to be executed
            return value;
     }
    myFunctionName(argument1, argument2);
    
  • Example:

      function sumOfNumbers(num1, num2) {
            let sum = num1 + num2; 
            return sum;
      }
     let result = sumOfNumbers(10,20);
    
  • Here we are also, storing result in a variable.

Why are functions so important?

Functions allow us to reuse code and create different modules to perform some procedures we plan on using repeatedly (solution to the problem of code duplication). Also, a complex problem is generally more managable when broken down into simpler subproblems. Then the program will be easier to understand and to update than the sequntial one.

Loops:

  • Loops are another fundamental building block that allow us to run a procedure repeatedly.
  • While Loops:

    • Syntax:

        while ( condition ) {
          // code block to be executed
        }
      
    • In the while statement, if the given condition is true, the code block will execute. Once the program has executed, it will go back to the beginning of the while statement and check if the condition is still true. If it is, the code will once again execute. This will continue happening (the execution of the code block loops) up until the while statement’s condition becomes false.

    • Translation: As long as the logical expression is true, repeat the instructions.

  • for-loops:

    • syntax

       for (initialization; condition; incrementation) {
          // code to run while the condition is true
       }
      
    • Initialization only happens once, when the code starts executing. It’s sets the initial value of the variable (program counter) in to the loop condition.

    • The condition is always evaluated once before the loop runs each time. If it’s true, the code runs but if not, the code doesn’t run.

    • The incrementation is evaluated after the loop runs each time. It’s often used to update the value of the variable associated with the loop condition.

    • In for loops the only change is that all the statements that are related to the “state” of the loop are grouped together after for.

    • The loop counter

      • The variable used during initialization, condition, and the final expression of a loop is called a counter and is often named i. This counter can be declared in the loop initialization to limit its scope to the loop body.

When should I use a for loop and When should i use a while loop?

For loops are great because they include the counting of the varible by default. However, it means you have to know how many times you want the loop to run as soon as you write your code. For situations where you don’t already know how many times the code should run, while loops make sense. while-loops, are usually used when we need to do a set of operations until a certain condition is met. if you know in advance how many times (how many increments) you want the loop to run, for is the best choice.

Arrays

  • A array is a variable that can store multiple values. Those values are accessed using a numbered indexing. An array is created with a pair of square brackets [].
  • Syntax: Declaring an array

     let array_name = [item1, item2, ...]; //  Declaring an array 
    
  • You can also assign values when creating the array by including them in between the brackets, with commas separating the values. The values in an array can be accessed by writing the name of the array followed by an index position with the following syntax:

    • let name = array_name[indexValue]; // Accessing Array Elements
  • Arrays are zero indexed, meaning the first item in an array will have an index of 0, the second item’s index will be 1, and so forth.

Objects:

  • Think about objects in the non-programming sense, like a car. A car can have different colors, they are manufactured by different people, with different companies, with different fuel type and many other properties.
  • Object-oriented programming (OOP) is a way to write programs using objects. Object-oriented programming is nothing but the capability to represent any real world object (real object with any object that you can see through a naked eyes).
  • So, in programming terminologies object is another variable that allows us to store multiple pieces of data. Allow you to “group” related data together and split your code into logical pieces.
  • Syntax:

     let objectName = {
        key: value,
        key: value,    
     };
    
  • An object is declared using curly braces {}. Properties and their values are stored within the curly braces, separated by a colon (:). Each property is separated by a comma (,), which comes after each property’s value. Each property is a key/value pair.

  • Order of properties doesn't matter in an object.

  • We access values in objects using keys, unlike in arrays. There we access it using index value (number). We can aslo have number's as a key in objects. The values inside an object are called object's properties

    • objectName.propertyName

Resources / references

Eloquent JavaScript

JavaScript

The Modern JavaScript Tutorial

JavaScript Tutorial

Conclusion

Remember : There's so much to learn, but it's all achievable if you don't give up.

By the way, if you didn’t know, everything taught in this tutorial as well as anything you need to know about vanilla Javascript, HTML, CSS and more, you can count on MDN to have an extensive amount of knowledge on it.

Let me know what you think about this article, and porgramming in general, through my Twitter and LinkedIn handles. I would love to connect with you out there!

Don’t forget to like & follow if you enjoyed! More articles coming soon! :)

Peace!

Top comments (6)

Collapse
 
abdulrahmanemad profile image
AbdulrahmanEmad

wow!
Really appreciate it. you have collected mostly all the programming concepts just in one article. It is really crucial, and useful for every beginner to read this article before diving into programming, and for non-beginners too to refresh memory

Collapse
 
prerana1821 profile image
Prerana Nawar

Thank you so much abdul. Means a lot !!

Collapse
 
cdthomp1 profile image
Cameron Thompson

This is great for beginners!

Collapse
 
prerana1821 profile image
Prerana Nawar

Thanks a lot Sir!!

Collapse
 
manuelbarzi profile image
manuelbarzi

more than variables seen as containers i would suggest to be seen as arrows pointing to things (values). variables are never containers, but references to values.

Collapse
 
prerana1821 profile image
Prerana Nawar

Ohh Yes Thank you, I will research on this, & will change it!