Category Archives: JavaScript

Back to Basics: Scoping And Hoisting

So, fellow JavaScript developers, my name is Fox Reymann, and tonight I’m going to present a talk, Ace JavaScript Interviews, Scoping and Hoisting. If any of you think the talk is too simple, let me start with a quiz. I have some code here, and as you can see, there’s a function. I’m running the function. I could…yeah, okay. So, we have an anonymous function. Okay, I have a function. I’m running the function, and I’m console logging x. So, what is going to be console log when I run this program? You have 10 seconds to look at the code and think. Okay, who’s for 10? Okay. Okay. Who’s 1? Undefined? Gs? Okay, so, yes, it’s 10, so no. Yes and no. It’s not Gs, not 1, not undefined. It’s 10. If you don’t know why, you will understand after the talk. If you listen carefully, yes. So, scope is a visibility of variables defined in one part of the program to another part of the program. So, if you have a variable A, can you use it above in the code, below in some function in a class, anywhere. So, here in my program, I’m defining a variable a. What would be the scope of this variable? Yes, it’s global. Now, there’s a function B, variable B. What is going to be a scope of this variable? – [Men] [Crosstalk] – Function scope, correct. This will be visible everywhere in this function, here, here, and also here. Yes, perfect. Boom, boom, boom. Function c, we are defining a variable with “let” and the constant with “const.” What is going to be a scope of these two, of this variable and this constant? – [Crosstalk] – A statement scope, you don’t call it a statement. Yes, please? – [Inaudible: 00:02:49] – Block, yes. Do you know why they change this [inaudible 00:02:54], and now it’s a block scope? – [Inaudible: 00:02:57] – I don’t know, but I think they tried to make it just more similar to other programs, I think, just so guys from Java C# can…they can think that…they can understand JavaScript. They don’t understand it anyway, because you need to understand JavaScript to understand the JavaScript, but they tried to make some attempt to make JavaScript more like Java? Stupid idea, and yes, so, now there’s another example. Function D, I’m running function D, and I’m console logging D. What is going to be console logged? – [inaudible 00:03:37] – Error, reference error, correct. Let me just prove it to you. I need to just comment out this console log before, so, where’s the function D? Blah, blah, blah, blah, blah. Function D. Reference error D is not defined, yes. Sorry, guys, my F function doesn’t work. Enter my bash profile. Okay, so, I’m going to comment this statement. What is going to be console log now? – [Crosstalk] – Undefined, yes. Most people say it’s undefined, yes. That’s correct. Do you know why? – [Inaudible 00:04:31] – No, no, no. I… I’m giving the talk. I will explain. This is because of hoisting, behavior specific to JavaScript, which means moving declarations of variables to the top of their scope. So, in this case, declaration of definition, declarations of this variable is here, because this variable has a function scope. And here in the code, the [inaudible 000:05:04] is defined with 10. So, when you declare a variable, it’s declared, but it’s undefined. You console logged it. It’s undefined in here, so now when I will run the program, it will say undefined. You can see it here. Okay, let me just comment it out. Next, boom, boom, boom, boom, boom. What’s going to be console logged? What’s going to happen? – [Inaudible 00:05:38] – Correct, because this function is also hoisted. So, in program languages without hoisting, you do B in error, but here this function is moved to the top of the current scope, so, to the top of the program even before the title of the talk. Now a function FF. – Undefined. – Undefined, you say. – [Crosstalk] – Yes, I got you. Nobody knows, okay. Yeah. – [Crosstalk] – No, the function is the closest answer. Yes, I will show you FF is not a function type error, yes, because this variable is declared at the top of the program, somewhere at the top. And here the function is being assigned to this variable. Here it’s undefined. You try to run undefined as a function, and you have a type error. Oh, nothing else, almost the end of the talk. Now I will explain you why this is 10. Now all of you should understand why this is 10, even guys that thought it’s 1 or Gs. So, in this code, this variable, X, is a function scope. New to hoisting, it’s being declared in here. After declaration it’s being undefined. Now give this statement which says if not X, so, if not undefined, which is equal to true. So, each statement is being executed. X is 10, and now when I console log, yes, it’s 10. Thank you, guys.

Back to basics of JavaScript.

Importing CSS Breakpoints Into Javascript

A quick and easy solution to this problem is to have your JS import the breakpoints directly from the CSS values in the DOM. This solution brings the current breakpoint variable into your JS in a way that’s:

  • Simple & Lightweight
  • DRY
  • Compatible with all browsers that support media queries (IE9+)


See Lullabot article, Importing CSS Breakpoints Into Javascript

4 Keys to a Clean Angular Implementation

tldr

  1. Modify all model properties in the controller rather than the view; let the view have access to the capability via controller functions.
  2. Keep all magic values (if you must have them at all) in the controller accessing them in the view via controller functions.
  3. Evaluate all comparison, computation, and logical expressions in the controller, giving the view access to them via controller functions.
  4. Pass to a controller function only what it does not already know: the loop parameter if in a loop, or no parameters at all if outside of a loop.

4 Keys to a Clean Angular Implementation

The Friendship Algorithm in JavaScript

I’m a big fan of The Big Bang Theory and I couldn’t resist playing around with Sheldon’s friendship algorithm. It’s pretty much one object represented as Sheldon guided by the module pattern (thanks to Addy Osmani).

I encourage you to fork this code and get some zen coding in. Since the logic is “safely” protected by Sheldon, you should be able to integrate any boilerplate of your choice for some fun interfaces. Also, feel free to refactor the logic when needed. It could always be better. That said, kudos to Wolowitz for plotting out the loop counter and escape.

The Friendship Algorithm

You can also view the demo here, here.

Chase down rogue console.log(); statements

Find console.log(); statements line-by-line by loading this JavaScript snippet to the top of your code (the higher the better):


['log', 'warn'].forEach(function(method) {
  var old = console[method];
  console[method] = function() {
    var stack = (new Error()).stack.split(/\n/);
    // Chrome includes a single "Error" line, FF doesn't.
    if (stack[0].indexOf('Error') === 0) {
      stack = stack.slice(1);
    }
    var args = [].slice.apply(arguments).concat([stack[1].trim()]);
    return old.apply(console, args);
  };
});

Be sure to remove this before entering production!

Thanks to, Remy Sharp.

What’s an Object in JavaScript?

Almost everything is an object.

  • Primitives: numbers, booleans, strings, null, undefined
  • Objects: Math, Date, JSON, window, document, objects you create, array, function, numbers, booleans, strings

Functions are “first class” values.

  • Assign a function to a variable.
  • Store a function as a value in an array or object.
  • Pass a function to a function.
  • Return a function from a function.

Primitives don’t look like objects.


var phoneNumber = "555-1212";	//phoneNumber is a primitive.
console.log(phoneNumber.length);//Now we need phoneNumber to be an object.
/*********************
*	BEHIND THE SCENES
*
*	phoneNumber is converted to a string object.
*	.length property is then accessed
*	
**********************/	
console.log(phoneNumber);		//phoneNumber is a primitive again.

Dos and Don’ts in JavaScript

Best Practices:

  • Choose short but readable variable names.
  • Avoid global variables.
  • Use only one global object to encapsulate any global variables you really need.
  • Always use var to declare your variables.
  • Indent your code so it’s readable.
  • Use curly braces to define blocks of code.
  • Comment your code.
  • Always use semi-colons.
  • Be aware of where automatic semi-colon insertion happens.
  • Declare variables outside loops.
  • Reduce DOM operations.