Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How is it possible that Regex can change a const?

I am a little confused by this video. I get that regex functions can be used to test constants but I was surprised as it looks like the regex used on a constant changed the constant. (***The example shared was modifying corn dog to hot dog.)

I thought that constants are not change-able?

Can someone please help me better understand?

1 Answer

Steven Parker
Steven Parker
243,318 Points

You didn't provide a link to the video, but without seeing it I would guess that you may have misinterpreted the demonstration. My guess is that the regex is being used to create a changed copy of the constant but the original constant remains unmodified.

Please provide a link to the video and an approximate time reference if that doesn't explain it.

Hi Steven--

Sorry about that, I had thought the question was being asked out of the video in question.

Here is the link:

https://teamtreehouse.com/library/using-regular-expressions-in-javascript

I was doing great until right about 2:03 where they were changing the const string1. I really thought that this would throw an error as it was set up with a const and not a let.

Thanks for taking time to help me understand! :)

Steven Parker
Steven Parker
243,318 Points

It looks like I guessed correctly. According to the MDN page on the replace method:

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
 
Note: The original string will remain unchanged.