Full-Stack Web Developer with a passion for learning Ruby, Rails, JavaScript, SQL, React, Redux, HTML, CSS, Bootstrap LinkedIn | GitHub | My Website (built with React)
Don't wanna be here? Send us removal request.
Text
JavaScript Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a “sub-program” that can be called by code external or internal to the function to perform a task. A function is composed of a set of statements called the function body. Values can be passed to a function and a function can return a value. A function must be called (invoked) for it to perform the specified tasks. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object.
Define a Function
There are several ways to define a function in JavaScript.
Function Declaration
A function declaration begins with the keyword function and is followed by
· the function name,
· a list of parameters to the function, enclosed in parentheses and separated by commas,
· the JavaScript statements that define the function, enclosed in curly brackets, {...} also called function body.
Note: Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. In the above code, a & b are the parameters whereas 60 & 120 are the arguments.
Function Expression
This form of defining a function does not require a name after the function and such a function can be called anonymous function as it does not have a name. Function are typically referenced through a variable:
The function expression is almost identical to the function declaration except for the missing name and the semicolon at the end. Another difference is that function declarations are hoisted to the top of the context when the code is executed, whereas function expressions are not hoisted.
Note: Hoisting is the process of moving a value to the top of the code block where it is used, regardless of where it is defined.
So, you can define a function after it is used in code without causing an error. Here is an example:
Trying the same thing with function expressions will result in an error:
Arrow Functions
Arrow functions are defined with a new syntax that uses an arrow (=>). The arrow comes after the list of parameters and is followed by the function’s body.
While they are like the function expressions, arrow functions have a few key differences:
If the arrow function is all on 1 line - an implicit return is added (you do not need the keyword return).
If the arrow function is on more than one line, {} must be used (just like a regular function)
If the arrow function takes 1 argument, you do not need to wrap that argument in parentheses (though for multiple arguments, you do)
Arrow functions are always anonymous
An arrow function does not have its own “this”; the “this“ value of the enclosing execution context is used.
Example without the arrow function:
In the above example, “this” is inside a declared object dog, but since the setTimeout() function is called at a later point in time, the keyword “this” does not refer to the parent object, it actually refers to the GLOBAL object which is the WINDOW object. Hence dog.sayHi() returned “Hi, I am undefined”. We lost the context of the keyword “this” in this example.
Example with arrow function:
In the above code, the arrow function keeps its value from the enclosing context. , It will refer to the “dog object”, and calling dog.sayHi() will work as expected and return “Hi, I am Oscar”.
Invoking a function
Defining a function does not execute it. Defining it simply names the function and specifies what to do when the function is called.
Invoking a function is to run the code inside the function’s body. To invoke a function, enter its name followed by parentheses – name().
Function Return Values
All functions return a value, which can be specified by the return keyword. If no return value is specified, the function will return undefined.
Summary
A function is a “sub-program” that can be called by code external or internal to the function to perform a task
They are several ways to define a function : function declaration, function expression, using arrow syntax
Function declarations are hoisted to the top of the context when the code is executed, whereas function expressions are not hoisted.
All functions return a value, which can be specified by the return keyword. If no return value is specified, the function will return undefined.
Defining a function does not execute it. To execute a function, it must be invoked
Any parameters a function needs are set when the function is defined whereas arguments are provided to the function, when in is invoked.
Thanks for reading.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
0 notes
Text
React Components
React is a library used to create user interfaces. React utilizes components to describe a portion of user interface. Components are independent and reusable bits of code. According to React documentation, components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
There are two ways to declare React components:
Using React createClass() method
Using ES6 classes
Using React createClass() method
Using ES6 Classes
In the above code, a new class Library is declared, and the class extends React.Component which provides built in properties and attributes.
Types of components
React lets you define components as classes or functions.
Class components
A class component requires you to extend from React.Component (this statement creates an inheritance to React.Component and gives your component access to React.Component's functions) and create a render() function. React.Component is the base class for React components when they are defined using ES6 classes.
Class components are stateful, ie., they can manage local state (Note: React has a built-in object called state, which allows components to create and manage their own data). setState() method and life cycle methods can be used in class components. Class components can be used as container components as they can deal with state and logic.
Functional Components
A functional component is a plain JavaScript function which accepts props (which stands for “properties”: object argument with data) as arguments and returns a React element.
A functional component does not extend React.component and hence is stateless, and setState() and life cycle methods cannot be used. A functional component returns JSX (syntax extension to JavaScript), instead of using a render() method. Functional components can be used as presentation components as they are only concerned with displaying content.
Summary
React components are small, reusable pieces of code that return a React element to be rendered to the page.
Class Components
Stateful
Life cycle methods and setState() method (https://reactjs.org/docs/react-component.html#setstate) can be used
May contain logic
Can be used as container components
Functional Components
Stateless
Life cycle and setState() methods cannot be used
Can be used as presentational components
Thanks for reading.
References
https://www.w3schools.com/REACT/react_components.asp
https://reactjs.org/docs/react-api.html#reactcomponent
https://reactjs.org/docs/jsx-in-depth.html
1 note
·
View note
Text
CSS DISPLAY PROPERTY: INLINE, BLOCK, INLINE-BLOCK, NONE
The CSS display property defines how an element takes up space in the layout. Browsers see every element on the page as being contained in a rectangular box and using display property, we can define how the elements should be seen or not seen in layouts. According to MDN “ The display CSS property sets whether an element is treated as a block or inline element and the layout used for its children, such as flow layout, grid or flex”. Most elements have either block or inline display values.
There are many values of the display property (The default value of display property is inline.), but these are the most commonly used:
Inline
This is the default value of display property. Inline elements do not start on a new line, they are displayed side by side. They take up only as much space as needed. Height and width properties cannot be set on an inline element.
Examples of inline elements include: <a>, <img>, <strong>, <span> etc.
Here is the output:
As you can see as <span> is an inline element, both the sentences are on the same line.
Here is another example:
Here we set the display property of <p> element (which is by default a block element) to inline because of which both the sentences are seen on the same line. The width and height properties have no effect as the display value is inline.
It is common practice to display <li> elements (which by default are block elements) as inline elements to turn a list into a horizontal navigation bar.
Here is the output:
Block-level
Block-level elements always start on a new line and take up the full width available. Width and height properties can be set.
Examples of block-level elements include: <div>, <p>, <h1>to<h6>, <ul>, <li> etc.
Here is an example:
When do not set the width and height properties, the block level elements take up all the available space.
Here is another example with width and height properties:
Inline-block
Inline-block shows both the characteristics of inline (will not start on new line) and block-level (will allow us to set width and height properties ) elements.
Here is an example:
Here is the output:
None
We can hide an element by setting the display property to none. The element will be hidden, and the page will be displayed as if the element is not there.
The second paragraph is hidden.
We can hide an element using visibility:hidden; However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:
The second paragraph is hidden, but the space it occupied is still visible.
Summary
Inline elements:
· Do not start on a new line
· Take up as much as space necessary
· Height and width properties cannot be set
Block elements
· Start on a new line
· Take up the full width available
· Height and width properties can be set
Inline-Block:
· Do not start on a new line like inline elements
· Height and width properties can be set like block elements
We can hide an element using display: none.
Thanks for reading.
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/display
https://www.w3schools.com/cssref/pr_class_display.asp
https://www.w3schools.com/html/html_blocks.asp
0 notes
Text
What is “this” in JavaScript?
“this” is a reserved keyword in JavaScript and its value is determined by how a function is called. According to MDN the value of “this” is “A property of an execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.”
Value of “this” in Global Context (Default Binding)
In global context (ie., ‘this’ is outside a declared object), the value of “this” is the GLOBAL object (window if in the browser) or UNDEFINED in the STRICT MODE.
Now let us look at this function which is not inside of a declared object:
In the above function, the value of ‘this’ is again the GLOBAL OBJECT (‘window’ object inside a browser) as it is not inside of a declared object.
The value of “this” in STRICT mode is UNDEFINED:
Value of “this” in object context (Implicit Binding)
If “this” is found inside a declared object, the value of “this” is always the closest parent object.
In the above code “this” is inside the object dog, therefore the value “this” will be the object dog.
Let us look at another example:
In the above example we added another object “master” inside of dog object and the value of ‘this’ changed because now “master” is the closest parent object and hence when we call dog.master.greetpet(), the output returned as “Hello undefined”. And the dog.master.findThis() returns false as dog object is no longer the “this”. The value of “this” is now the master object.
Changing “this” using explicit binding
We can change the value of “this” using the three function methods, namely, call(), apply(), and bind().
Call() method
The first argument to the call() method is whatever you want the value of the “this” to be and this is usually called ‘thisArg’. The call() method calls a function with a given this value and arguments provided individually.
The arguments after ‘thisArg’ are any parameters that you want to pass to the function which you are changing the context of keyword ‘this’ inside of. And since a function can have any number of arguments, the arguments are separated from one another with a comma. When the call() method is used on a function, that function is immediately invoked.
Now let us look at the same example as above, but this time calling the function using call() method:
When we invoke the greetPet() function, the first parameter to call() method is what we want the keyword ‘this’ to refer to. In the above code, we are setting the value of ‘this’ to be dog object. Now you can see from the output that it is no longer “undefined”.
Apply() method
The syntax of apply() method is same as call() method except that call() accepts an argument list, while apply() accepts a single array of arguments.
And like call() method, when apply() method is used on a function, the function is invoked immediately.
In the above code, we use apply() method to set “this” to dog1 or dog2.
Bind() method
Bind() method is like call() method except that instead of invoking the function immediately, it returns a function definition. According to MDN “The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called”.
Bind can be used to set the context of “this” for a function that will be called at a later point in time, like setTimeout() method.
In the above example, “this” is inside a declared object dog, but since the setTimeout() function is called at a later point in time, the keyword “this” does not refer to the parent object, it actually refers to the GLOBAL object which is the WINDOW object. Hence dog.Hello() returned “Hello undefined”. We lost the context of the keyword “this” in this example. We can use bind() method to set the keyword “this” to the dog object.
We passed “this” as the first argument to the bind() method, and that is because inside of dog object, the keyword “this” refers to the dog object.
Using the keyword “new” to set the value of “this”
The new keyword does the following things:
o Creates a blank, plain JavaScript object;
o Links (sets the constructor of) this object to another object;
o Passes the newly created object from Step 1 as the “this” context;
o Returns “this” if the function does not return an object.
In the above example, the keyword “this” inside the function is not part of a declared object, hence its value refers to the GLOBAL OBJECT which is the WINDOW object in this case.
The value of keyword “this” changes when we use the “new” keyword. The value of “this” refers to the object that is created when the “new” keyword is used. We stored the value of the object in the variable oscar and used it to access the firstName, breed, and age properties on it.
Summary
The keyword “this” is a reserved keyword and its value is determined at execution.
It is set either using GLOBAL context or OBJECT BINDING(IMPLICIT BINDING) or EXPLICIT BINDING (call(), apply(), bind()) or the “new” keyword.
When “this” is in the global context or in a function it is either the GLOBAL OBJECT (WINDOW object if in the browser) or UNDEFINED (in STRICT MODE).
When “this” is inside of a DECLARED OBJECT, the value of “this” is always the CLOSEST PARENT OBJECT. We can use the keyword “new” to set the value of “this”.
Thanks for reading.
References: https://developer.mozilla.org/en-US/
0 notes
Text
“Self” in Ruby
What is “self”?
“Self” is the current object. The object to which a method is applied or the object which receives the method call is “self”. The current object depends on the context.
To know which object is “self”, we need to know what context the program is in at given time. As a program runs, its context constantly changes. Context is where your code is now as the program runs.
Self at the top level of the program(outside any class or module)
So, what is “self” when program execution is at top of the program and is outside of any class or module definition block?
As you can see in the above code the output for self is “main” . In Ruby, the object at the top level is called “main” and is an instance of Object class. So “main” is the top-level context of the Ruby program.
And the same applies to a method that is defined at the top level of the program:
Methods defined at the top level are bound to the “main” object.(Note: You will notice “nil” being returned at the end in the above code, that is because “puts” always returns “nil”).
Self inside class or module definitions
“Self inside a class refers to the class object.
Similarly, “self” inside a module refers to the module object.
Self inside an instance method definition
But when we define a method inside a class, “self” is the object that gets created(Library.new) ie., an instance of the class.
The output #<Library:0x0000557821504418> indicates that it is an instance of class Library. In the above code the variable “library” is the receiver of the message “books” (Note: Calling methods or sending messages to objects involves dot notations --> library.books).
Self inside a class method
Since it is a class method, “self” refers to the class.
Self inside a Singleton method
Methods you define for a single object are called singleton methods. “Self” here is the object that owns the method.
Summary
So “self” in Ruby is a reserved keyword that refers to the default object. The value of “self” depends on the execution context.
Thanks for reading.
0 notes
Text
Variable declarations: var, let, const in JavaScript
Variables are a way of storing a value for future use. There are 3 ways to declare a variable in JavaScript, namely, var, let and const. var, let and const are keywords in JavaScript.(Note: Variable names can start with any upper or lower case letter, an underscore(_), or dollar symbol ($). It can also contain numbers, but cannot start with them.)
var
Variables declared with “var” are scoped to the current execution context (Note: Scope is where a variable is visible and accessible), ie., a variable’s enclosing function or global scope (accessible everywhere in the program).
When using “var” to declare a variable, initializing is optional.
To assign a value to the variable, use the = operator:
Can be reassigned at any point:
Variables declared with “var” can be redeclared at any point. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.
var declarations, regardless of where the actual declaration occurs, are processed before any code is executed. This is called hoisting. The declaration of the variable is hoisted to the top, and the initialization remains in the original spot.
In the above code, dogBreed could be accessible outside of “if” block, as the variable dogBreed is scoped not just to the “if” block but, to the entire function. But when we try to access it outside the function, we get a reference error (ReferenceError: dogBreed is not defined).
Now when we call the function again after changing the value of condition to “false”, we can see that dogBreed is “undefined” both from the else clause and outside of “if-else” block. This is because variables declared using “var” are hoisted to the top of the code, but not the value. Hence the variable declaration dogBreed is accessible inside of “else” clause and outside of “if-else” block. Since the value is not hoisted, the variable dogBreed would just have a value of “undefined”.
Summary of “var”:
· Scoped to the current execution
· Initializing with a value is optional
· Can be reassigned
· Can be redeclared
· Variable declarations with “var” are hoisted
let
The “let” declaration syntax is the same as the syntax for “var”. Like “var”, initializing is optional.
Assign a value using = operator:
Can be reassigned:
Cannot be redeclared (in the same scope):
No error is thrown if the variable is declared with same name using “let” in its containing scope:
Variables declared with “let” are not hoisted to the top of the code and are block scoped (ie., inside a function or inside a block --inside {} braces):
In the above code, variable dogBreed is no longer accessible once the execution flows out of “if” block. This is because dogBreed was declared using “let” and so is not hoisted to the top of the code.
If the condition evaluates to false, then the variable dogBreed is never declared or initialized:
Summary of “let”:
· Block scoped
· Initializing with value is optional
· Can be reassigned
· Cannot be redeclared in the same scope
const
“const” stands for constant and is block scoped like “let”. Variables declared using “const” must be initialized upon declaration and cannot be reassigned or redeclared. Just like “let”, variables declared with “const” are not hoisted to the top.
A “const” declaration prevents the modification of binding, not of the value. [According to MDN “The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned”]. That means that “const” declarations for objects and arrays do not prevent modification of those objects and arrays.
Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.
Summary of const:
· Block scoped
· Must be initialized upon declaration
· Cannot be reassigned
· Cannot be redeclared
It is better to use “const” by default and use “let” when you know a variable’s value needs to be changed.
Thanks for reading.
0 notes
Text
LOOPING IN RUBY
Programming construct called Looping can be used to repeat code, for example, a code that might ask for user’s input repeatedly. So, looping occurs when you tell a program do something a certain number of times. These are some of the methods to loop, namely, Loop, Times, While & Until.
Let’s look at these methods.
The Loop method is the simplest looping construct in Ruby. It starts with a loop keyword followed by do and end with code block (delimited set of program instructions) between them. It doesn’t take any arguments. Here is an example-
loop do puts “I can do this forever” end
It can also be written using curly braces-
loop {puts "I can do this forever"}
The above code creates an infinite loop which might crash our computers. And that is not something we would want our code to do. We can control the loop using break keyword-
loop do puts "I am not going to run forever" break end
The above code runs exactly once as the
break
keyword ends the loop.
We can use a counter to tell our code to run certain number of times –
#start a counter & set it to 0 outside the loop counter = 0 loop do puts "I am counter number #{counter}" # increment the counter by 1(current value of counter + 1) counter = counter + 1 # If our counter is 10 or more if counter >= 10 #stop executing the loop break end end
The above program will run 10 times-
I am counter number 0 I am counter number 1 I am counter number 2 I am counter number 3 I am counter number 4 I am counter number 5 I am counter number 6 I am counter number 7 I am counter number 8 I am counter number 9 => nil
times is another construct for looping. It is an instance method of class Integer, which means it must be called as a method on integers. It will execute the block a certain number of times which is dependent on the number that is called. And at the end of the method, it will return the integer it was called on. Here is an example-
4.times do puts "The rain in Spain stays mainly in the plain!" end
It will execute the code exactly 4 times and returns 4 at the end
The rain in Spain stays mainly in the plain! The rain in Spain stays mainly in the plain! The rain in Spain stays mainly in the plain! The rain in Spain stays mainly in the plain! => 4
The while construct method will execute a block as long as a specific condition is true. The block starts with a while keyword and ends with end. The code between while and end is the body of the while loop. Here is an example-
counter = 0 while counter <= 10 puts "I am counter number #{counter}" counter = counter + 1 end puts "Done"
The above code runs as long as the condition counter <= 10 is true. With each iteration, the counter is incremented by 1 and when the counter becomes 11 (it is no longer <= 10) the condition becomes false and the loop terminates.
I am counter number 0 I am counter number 1 I am counter number 2 I am counter number 3 I am counter number 4 I am counter number 5 I am counter number 6 I am counter number 7 I am counter number 8 I am counter number 9 I am counter number 10 Done => nil
The until construct is the opposite of while, that is, the code following until will execute while the condition is false or until the condition is true.
counter = 1 until counter > 10 puts "I am counter number #{counter}" counter = counter + 1 end
The code executes as long as the condition counter > 10 is false or until the condition is true which is when the counter becomes 11 which is greater than 10.
I am counter number 1 I am counter number 2 I am counter number 3 I am counter number 4 I am counter number 5 I am counter number 6 I am counter number 7 I am counter number 8 I am counter number 9 I am counter number 10 => nil
That’s it for now. Hope that makes sense.
1 note
·
View note