Discussion, Questions, and Resources for Part 1 (JavaScript - April 2018 Cohort)

Started today, and about halfway through basic. I’d like to finish today if possible. I’ve already done the FCC front end curriculum up to the front end intermediate projects. However I have struggled quite a bit on codewars, and i’m thinking I need to go back over some stuff. However the beta stuff looks really good!

Anyone know how the beta and legacy stuff will be handled? will one impact the other?

sorry - should have searched first. if anyone else was wondering, check out these links.

1 Like

Strict Mode

I wasn’t familiar with "use strict" (i.e. Strict mode) so I looked it up.

In ES6: Explore Differences Between the var and let Keywords, it states:

Note the “use strict”. This enables Strict Mode, which catches common coding mistakes and “unsafe” actions.

That’s helpful, but is it necessary to use it? What are the suggested best practices?

According to MDN’s Strict mode page:

ECMAScript 5’s strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of “sloppy mode”. Strict mode isn’t just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don’t rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

Here are some other resources about Strict mode that might be helpful:

In general, it seems to be best practice to use Strict mode on new projects but not necessarily to add it to existing projects.

map(), filter(), and reduce()

So, unfortunately, freeCodeCamp Beta doesn’t do a great job of introducing the map, filter, and reduce functions before they’re needed. Here’s a quick summary:

  • map()
    MDN map() page | fCC Guide on map()

    The map() method creates a new array with the results of calling a provided function on every element in the calling array.

    Example:

    var numbers = [1, 4, 9];
    var roots = numbers.map(Math.sqrt);
    // roots is now [1, 2, 3]
    // numbers is still [1, 4, 9]
    
  • filter()
    MDN filter() page | fCC Guide on filter()

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    Example:

    const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];
    
    let longWords = words.filter(word => word.length > 6);
    
    // Filtered array longWords is ["exuberant", "destruction", "present"]
    
  • reduce()
    MDN reduce() page | fCC Guide on reduce()

    The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    Example:

    var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
       return accumulator + currentValue;
    }, 0);
    // sum is 6
    

:sunny:

2 Likes

Just want to hop in here and emphasize how useful these functions are, especially map and filter. I’m working on a masters in Cartography and one of my current courses heavily emphasizes D3 so I jumped ahead to work some of the data visualization projects. These functions were invaluable in completing the projects that I did. Basically what i’m saying is don’t skip on fully learning these, you’ll need to understand them.

2 Likes

Where do you think we should best introduce each of these concepts in the flow of freeCodeCamp’s beta curriculum?

1 Like

If I may jump in here, these concepts are first passively mentioned in the ES6: Write Higher Order Arrow Functions lesson so it should probably be taught before that. I think somewhere at the end of the Basic JavaScript section - where some specific JS methods (random & parseInt) are introduced - makes the most sense.

2 Likes

hey guys,

anyone else having issues with this challenge? I’ve finally looked it up and entered the solution in, and its still not passing.


//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["JavaScript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(name, prop){
// Only change code below this line
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === firstName) {
      if (contacts[i].hasOwnProperty(prop)) {
        return contacts[i][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

OMG. thanks!! thats why I was getting the firstName is not defined error. good to go!

I feel like the regular expressions section could use more detailed explanations for why the Regex does what it does.

For example, the part that explains what “lookaheads” are is confusing me quite a bit. FCC says a lookahead tells JavaScript to look-ahead in your string to check for patterns further along, but then says it doesn’t actually match?
It then lists an example of how to validate a 3-5 character password that has at least one number, and I do not understand the why behind why this regex works, if it isn’t actually ‘matching’ the pattern.
/(?=\w{3,6})(?=\D*\d)/ .
Are lookaheads meant to be used when you want to match more than one pattern in a string? If so, typically would you use at least two or more lookaheads?

3 Likes

@RHoneyman87, That’s a good question. I think the use-case that’s being described in the Positive and Negative Lookahead challenge is one where the regex is validating the password, not returning matches for it. If I’m understanding it correctly, a regex that uses lookaheads for something like this is meant to return true or false, not an actual match. This is why the code in the challenge uses .test() instead of .match():

let result = pwRegex.test(sampleWord);

It’s not clear to me how to use lookaheads to aid in matching strings. :question: Maybe someone else can help with that. An example would be helpful.

I agree. That said, I found the regex section to be pretty good when I combined it with the RegExr and regex101 tools. Some of the challenges are just a matter of typing a word or two, others are more complicated and require more thought. Overall, I enjoyed the section and I learned a lot, both about regular expressions and about the regular expression tools. :hammer_and_wrench: :

If you or others are interested in more regex practice, here are some games and exercises:

For those interested in JavaScript security and regex, the freeCodeCamp YouTube channel recently posted a great video entitled Writing Secure JavaScript. At about the 12:18 mark, the presenter talks about denial-of-service attacks taking advantage of regular expressions (ReDoS) using Catastrophic Backtracking.

One way to prevent this:

To prevent catastrophic backtracking, you want to keep an eye out for anytime you’re using ‘+’ or ‘*’ operators within proximity to each other. If you are, chances are they’re going to end up in the type of tug-of-war that results in catastrophic backtracking. Make sure that both operators are in fact necessary. You can also consider replacing one of them with a limited set.

:sunny:

2 Likes

@RHoneyman87 @camper, I struggled with this quite a bit and I think I understand it now.

Generally, a RegEx expression used within the .test method asks the question ‘does anything in this string match expression regex?’. A lookahead pattern adds to this question and asks ‘does anything in this string that matches expression regex also have a match to expression lookahead further up in the string?’.
In both cases, what you want in return is just the part that matches regex and not the part that matches lookahead.

So when used with the .match method, the example below returns "Regular ", not “Regular expressions”.

let ourStr = "Regular expressions";
let ourRegex = /Regular (?=expressions)/;
ourStr.match(ourRegex); 

But if you change the expression to the one below, you will get null.

let ourStr = "Regular expressions";
let ourRegex = /Regular (?=stuff)/;
ourStr.match(ourRegex); 

What these examples demostrate is that even though I only get the word "Regular " returned, I will still only get it if there is the word “expression” somewhere further up (hence the name lookahead) in the string.

BTW, it should be clarified that a lookahead doesn’t really look for a match anywhere in the string ahead by default. It will look for a match right ahead of the previous part of the expression. That’s why I had to include the space in my regex, here:
/Regular (?=expressions)/;.
If you wish to look for the lookahead part anywhere further up in the string, you will have to add .* (period and asterisk) at the beginning of the lookahead statement, like this:
/Regular(?=.*expressions)/;.
Adding it before the lookahead statement will return the whole string up till the lookahead, like this:
/Regular.*(?=expressions)/;

I hope that clarifies it and that this is the correct explanation :blush: . I learned a lot while answering so thanks for asking :clap: .

3 Likes

@yoizfefisch Awesome answer! I think it should be added to the challenge. :white_check_mark:

So, would using the following regex and using .match() be a way to return the string that meets the criteria in the challenge example?

(?=\w{3,6})(?=\D*\d).*
1 Like

@camper @yoizfefisch
Thanks to both of you! Your explanations definitely helped.
I just started studying again this evening and the very next regex challenge Reuse Patterns Using Capture Groups also wound up confusing me! I figured it out this time.

It mentioned that you can wrap a regex in parentheses to find repeat substrings, and listed an example using \1 to repeat the (\w+) capture group. The challenge is to use two capture groups. I thought that you just had to use \2! Turns out \1 is literally pointing to the first capture group used. So you can use \1 over and over again to repeat the regex found in the first capture group. Using \2 would point to a second capture () group, not just use the same capture group twice. Hopefully if someone else gets confused by that as well and comes here, they’ll get it.

2 Likes

@camper What you are trying to do is get all the characters after any charcter that satisfies the lookahead. In this case it should be the complete string since the expression starts with the lookahead.

However, you are breaking the upper limit of 3-6 characters by adding a wildcard period and a 0-or-more asterisk…
It’s actually an interesting question and if anyone can think of a way to return the password with .match alone, I would love to hear.

1 Like

In the ES6 module talking about const, what are the rules regarding capitalization? The module mentions capitalizing but often does not. Shouldn’t we always capitalize const or did I miss something?

I’ve been working on several different React tutorials all of which use ES6 and none of them are using capitals for their const. In https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch2.md
he says

Essentially, const declarations enforce what we’ve stylistically signaled with our code for years, where we declared a variable name of all uppercase letters and assigned it some literal value that we took care never to change. There’s no enforcement on a var assignment, but there is now with a const assignment, which can help you catch unintended changes

but he doesn’t capitalize in the example…

1 Like

yeah that’s what’s tough - its kind of inconsistent.

There aren’t any. In some languages, constants are capitalised (generally by convention). When you see someone capitalising, it’s likely they’ve come from a language like C/C++/Ruby/similar

Const-correctness is an issue in imperative languages like C++ because by default name bindings typically create variables, which can vary, as the name suggests, and thus if one wishes to mark a binding as constant this requires some additional indication.

…hence CONSTS_ARE_WRITTEN_LIKE_SO so that you can see they’re a constant.

consts in JS generally are not capitalised: it doesn’t matter in JS, which works differently to C/C++/etc. You can use consts everywhere, they aren’t special, so it doesn’t really make sense to capitalise them unless you really like having AN_EXTREMELY_SHOUTY_PROGRAM, which is just going to annoy people reading your code

note classes are title cased, and that’s just convention as well, but that one you do need to stick to because it’s extremely confusing to anyone reading your code if there are Identifiers That Are TitleCased That Are Not Used For Classes.

1 Like

@nvrqt03 There are a couple of relatively well-known style guides you may want to use for your projects, or base your own style guides on for capitalization and other code styles:

  • Google JavaScript Style Guide

    Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. There is no reason for a constant to be named with a trailing underscore, since private static properties can be replaced by (implicitly private) module locals.

  • Airbnb JavaScript Style Guide

    23.10 You may optionally uppercase a constant only if it (1) is exported, (2) is a const (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change.

Both guides go into more detail about when and when not to capitalize, with examples.

1 Like

good find, thank you!!